content
stringlengths
42
6.51k
def parse_content_type(content_type, default_charset='utf-8'): """Parse content type value for media type and charset.""" charset = default_charset if ';' in content_type: content_type, parameter_strings = (attr.strip() for attr in content_type.split(';', 1...
def index(lst, trunc): """ Converts an n-ary index to a 1-dimensional index. """ return sum([lst[i] * trunc**(len(lst)-i-1) for i in range(len(lst))])
def parse_list_from_string(a_string): """ This just parses a comma separated string and returns an INTEGER list Args: a_string (str): The string to be parsed Returns: A list of integers Author: SMM Date: 10/01/2018 """ if len(a_string) == 0: print("No items fo...
def is_signed_message(message): """Returns true if the message contains our unique signature""" UNIQUE_SIGNATURE = "DLZ" if message[0] == UNIQUE_SIGNATURE: return True else: return False
def ca2s(cypher_array): """Takes a cipher array and converts it to a string of cipher texts instead of integers""" for i in range(len(cypher_array)): cypher_array[i] = str(cypher_array[i]) return "".join(cypher_array)
def _translate_vif_summary_view(_context, vif): """Maps keys for VIF summary view.""" d = {} d['id'] = vif['id'] d['mac_address'] = vif['address'] d['ip_addresses'] = vif['ip_addresses'] return d
def example_function_with_shape(a, b): """ Example function for unit checks """ result = a * b return result
def normalize_cycleway(shape, props, fid, zoom): """ If the properties contain both a cycleway:left and cycleway:right with the same values, those should be removed and replaced with a single cycleway property. Additionally, if a cycleway_both tag is present, normalize that to the cycleway tag. ...
def map_pairs(a_list, func): """For list [1,2,3,4] returns: [func(1,2), func(2,3), func(3,4)] Works only for lists. """ result = [] if a_list: head_item = a_list[0] tail = a_list[1:] while tail: next_item = tail[0] result.append(func(head_item, ne...
def find_codon(codon, seq): """Find a specified codon with a given sequence.""" i = 0 # Scan sequence until we hit the start codon or the end of the sequence while seq[i:i+3] != codon and i < len(seq): i += 1 if i == len(seq): return 'not found' return i
def user_info(user): """ Get the serialized version of a user's information. Args: user: The user to get the serialized information of. Returns: A dictionary containing the serialized representation of the given user's information. """ if not user: r...
def strConfig(config): """Stringifies a list of moosicd filetype-player associations. This function converts the list used to store filetype-to-player associations to a string. The "config" parameter is the list to be converted. The return value is a good-looking string that represents the content...
def clean(values): """ Clean up the value convert (100) to -100 """ if "(" in values: values = "-" + values.replace("(", "").replace(")", "") values = values.replace(",", "") try: return float(values) except ValueError: return values
def find_closest_points(some_list, a_number, num_of_points): """ some_list -> (list of ints) A list of x or y coordinates a_number -> (int) a specific number that will be our base num_of_points -> (int) how many numbers we should looking for """ some_list = sorted(some_list) closest_point...
def insertion_sort(arr): """ Insertion Sort Complexity: O(n^2) """ for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos-1] > cursor: # Swap the number down the list arr[pos] = arr[pos-1] pos = pos-1 # Break an...
def __assert_data_tuple(data, num): """Internal helper to ensure data is a tuple of given `num` length.""" if not isinstance(data, tuple): data = (data,) if not len(data) == num: raise AssertionError() return data
def gen_list_of_lists(original_list, new_structure): """ Generates a list of lists with a given structure from a given list. Parameters ---------- original_list : list The list to make into a list of lists. new_structure : list of lists (contains ints). Returns ---...
def segment_diff(s1, s2): """ Returns the sum of absolute difference between two segments' end points. Only perfectly aligned segments return 0 """ return abs(s1[0] - s2[0]) + abs(s1[1] - s2[1])
def get_ssml_string(text, language, font): """Pack text into a SSML document Args: text: Raw text with SSML tags language: Language-code, e.g. de-DE font: TTS font, such as KatjaNeural Returns: ssml: String as SSML XML notation """ ssml = f'<speak version="1.0" xmlns=...
def kinetic_energy(m : float, v : float) -> float: """ [FUNC] kinetic_energy: Returns the kinetic energy in Joules Where: Mass = m Velocity = v """ return (m * (v*v)) / 2
def ReadData( offset, arg_type ): """Emit a READ_DOUBLE or READ_DATA call for pulling a GL function argument out of the buffer's operand area.""" if arg_type == "GLdouble" or arg_type == "GLclampd": retval = "READ_DOUBLE(pState, %d)" % offset else: retval = "READ_DATA(pState, %d, %s)" % ...
def funct_worker(input_list,pre_text): """ Worker Function: define function that each process should do e.g. create string from content in input_list while begin with pre_text => "[pre_text] [input_list] """ output_string = f"{pre_text}" output_string = output_string + " ".join(input_list) ...
def compute_reference_gradient_siemens(duration_ms, bandwidth, csa=0): """ Description: computes the reference gradient for exporting RF files to SIEMENS format, assuming the gradient level curGrad is desired. Theory: the reference gradient is defined as that gradient for which a 1 cm slice is...
def flatten_filesystem(entry, metadata): """ Converts all nested objects from the provided metadata into non-nested `field->field-value` dicts representing filesystem metadata changes. Raw values (such as memory size, timestamps and durations) are transformed into easy-to-read values. :param entry...
def dict_create(text): """ Build dictionary with list of words from text """ dict = {'': ['']} for i in range(0, len(text)): if i < len(text) - 2: if text[i] + " " + text[i+1] not in dict: dict[text[i] + " " + text[i+1]] = [text[i+2]] else: di...
def rounding(v): """Rounding for pretty plots""" if v > 100: return int(round(v)) elif v > 0 and v < 100: return round(v, 1) elif v >= 0.1 and v < 1: return round(v, 1) elif v >= 0 and v < 0.1: return round(v, 3)
def clean_consonants(text): """ Removes nearby equal consonants if they are more than 2. Parameters ---------- text : str Returns ------- str """ consonants = ['b','c','d','f','g','h','k','l','m','n','p','q','r','s','t','v','x','y','z'] new_text = text words = text.sp...
def _get_workflow_name(json_spec, workflow_name=None): """ Returns the name of the workflow to be created. It can be set in the json specification or by --destination option supplied with `dx build`. The order of precedence is: 1. --destination, -d option, 2. 'name' specified in the json file. ...
def list2csv (l) : """ Converts a list to a string of comma-separated values.""" s = None if isinstance(l,list) : s = str(l[0]) for i in range(1,len(l)) : s += ','+str(l[i]) return s
def same_container(cont1, cont2): """ Return True if cont1 and cont2 are the same containers.We assume that processes that share the same PID are the same container even if their name differ. We assume that files that are located in the same directory and share the same inode are the same container...
def length(b): """ Returns the length of the first netstring in the provided bytes object without decoding it. WARNING: This function doesn't check for netstring validity. """ try: return int(b[:b.find(b':')].decode('ascii')) except: raise ValueError
def guess_service_info_from_path(spec_path): """Guess Python Autorest options based on the spec path. Expected path: specification/compute/resource-manager/readme.md """ spec_path = spec_path.lower() spec_path = spec_path[spec_path.index("specification"):] # Might raise and it's ok split_sp...
def b2tc(number: int): """ Funcion devuelve el complemento de un numero entero el cual se define como "inversion de todos los bits". :param number: numero entero :type number: int :return: cadena conforme a resultado inverso de bit (XOR) :rtype: str """ b2int = int(bin(number)[2:]) # [2...
def transform_from_local(xp, yp, cphi, sphi, mx, my): """ Transform from the local frame to absolute space. """ x = xp * cphi - yp * sphi + mx y = xp * sphi + yp * cphi + my return (x,y)
def revert_graph(G): """Returns a reverted version of the graph, where all the edges are in the opposite direction""" rev = [[] for _ in range(len(G))] for v, neighbors in enumerate(G): for w in neighbors: rev[w].append(v) return rev
def parseMemory(memAttribute: str) -> float: """ Returns EC2 'memory' string as a float. Format should always be '#' GiB (example: '244 GiB' or '1,952 GiB'). Amazon loves to put commas in their numbers, so we have to accommodate that. If the syntax ever changes, this will raise. :param memAttr...
def extend(a, b): """ extend :param a: :param b: :return: """ a[0] = min(a[0], b[0]) a[1] = min(a[1], b[1]) a[2] = max(a[2], b[2]) a[3] = max(a[3], b[3]) return a
def list_cycles(grammar, parent, length): """Unrestricted""" if length == 1: return [parent] return [ parent + x for node in grammar[parent] for x in list_cycles(grammar, node, length - 1) ]
def tolist(x): """convert x to a list""" return x if isinstance(x, list) else [x]
def time_key(file): """ :return: 'time' field or None if absent or damaged """ field = file.get('imageMediaMetadata').get('time') if field and len(field) > 5: return field return None
def _fix_docstring_for_sphinx(docstr): """ Remove 8-space indentation from lines of specified :samp:`{docstr}` string. """ lines = docstr.split("\n") for i in range(len(lines)): if lines[i].find(" " * 8) == 0: lines[i] = lines[i][8:] return "\n".join(lines)
def dictionary_merge(a, b): """merges dictionary b into a Like dict.update, but recursive """ for key, value in b.items(): if key in a and isinstance(a[key], dict) and isinstance(value, dict): dictionary_merge(a[key], b[key]) continue a[key] = b[key] return...
def mape(a, p): """Calculate the mean absolute percentage error.""" return abs(p-a) / a
def unhappy_point_lin(list, index): """ Checks if a point is unhappy. Returns False if happy. """ if index == 0: if list[index] == list[index + 1]: return False if index == len(list)-1: if list[index] == list[index - 1]: return False else: ...
def checkSha(firstSha, secondSha): """ This function checks if the two files that are to be merged have the same res """ if firstSha != secondSha: raise ValueError('\n\nCan\'t merge files!\nSha are different!') return True
def generate_url(internal_id): """ Generate url of article in Dokumentlager. @param internal_id: uuid of article @type internal_id: string @return url to get all data of one article """ template = "https://dokumentlager.nordiskamuseet.se/api/list/{}/0/500" return template.format(interna...
def indent(txt): """Indent the given text by 4 spaces.""" lines = ((" " + x) for x in txt.split('\n')) return '\n'.join(lines)
def make_prereq_level_check_formulas(skill, reqskill_level): """ Returns a list of formulas that check if each of the given skill's reqskills, if any, have a base level same or greater than reqskill_level. """ if reqskill_level <= 1: return "" reqskills = [skill["reqskill1"], skill["reqs...
def bond_yield(price, face_value, years_to_maturity, coupon=0): """ """ return (face_value / price) ** (1 / years_to_maturity) - 1
def is_number(x): """ Returns: True if value x is a number; False otherwise. Parameter x: the value to check Precondition: NONE (x can be any value) """ return type(x) in [float, int]
def flat_multi(multidict): """ Flattens any single element lists in a multidict. Args: multidict: multidict to be flattened. Returns: Partially flattened database. """ flat = {} for key, values in multidict.items(): flat[key] = values[0] if type(values) == list and ...
def get_subscribe_broadcast_messages(received_message, subscription_id, connection_id): """ Return a BroadcastMessage to be delivered to other connections, possibly connected through redis pub/sub This message is called whenever an user subscribes to a topic. """ assert received_message is not ...
def func(x, a, b, c, d, e): """Smooth help function""" return a*x + b*x*x + c*x*x*x +d*x*x*x*x +e
def radius_curvature(z, zR): """calculate R(z)""" # This could be smarter, just adding epsilon to avoid nan's if (z == 0): z += 1e-31 return z * (1 + (zR/z)*(zR/z))
def split_particle_type(decays): """ Separate initial particle, intermediate particles, final particles in a decay chain. :param decays: DecayChain :return: Set of initial Particle, set of intermediate Particle, set of final Particle """ core_particles = set() out_particles = set() for...
def init_layout(height, width): """Creates a double list of given height and width""" return [[None for _ in range(width)] for _ in range(height)]
def expected_value_test(context, value: str): """ Check if the context contain the expected value :param str context: The context :param str value: The expected value to find """ if str(value).__contains__('context'): split_value = value.split('.') expected_value = context.__get...
def format_time(time_us): """Defines how to format time in FunctionEvent""" US_IN_SECOND = 1000.0 * 1000.0 US_IN_MS = 1000.0 if time_us >= US_IN_SECOND: return "{:.3f}s".format(time_us / US_IN_SECOND) if time_us >= US_IN_MS: return "{:.3f}ms".format(time_us / US_IN_MS) return "{:...
def create_source_object(sources): """Format the source information as appropriate for the api""" if sources: source_object = [] srcs = sources.split("/") for ix, src in enumerate(srcs): source_object.append({ "source-name": src, "id": ix, ...
def is_eyr_valid(eyr: str) -> bool: """Expiration Year""" return 2020 <= int(eyr) <= 2030
def xml_escape(s): """Escapes for XML. """ return (("%s" % s).replace('&', '&amp;').replace('"', '&quot;') .replace('<', '&lg;').replace('>', '&gt;'))
def foundSolution(solver_result): """ Check if a solution was found. """ return "Valid" not in solver_result and "unsat" not in solver_result
def convert_class_functions(line): """Convert class initializer functions to the corresponding variable.""" first_paren = line.find('(') if first_paren == -1: return line if "initContainer" in line: line = line[first_paren + 1:] first_comma = line.find(',') if first_comma...
def rm_dsstore_list(list): """ ** Intended for macOS users who sorted files in Finder in any special way ** Removes the directories (strings) from an input list that contain .DS_Store in the string (therefore removes the directory to .DS_Store files) :param: list of directories :return: list of directories...
def all_subsets(aset): """Solution to exercise C-4.15. Write a recursive function that will output all the subsets of a set of n elements (without repeating any subsets). -------------------------------------------------------------------------- Solution: --------------------------------------...
def _flip_bits_256(input: int) -> int: """ Flips 256 bits worth of `input`. """ return input ^ (2**256 - 1)
def labelit(varname, vardict): """Return the variable label or, if none, the variable name varname is the variable to label. If none, return "" vardict is a VariableDict object""" if not varname: return "" return vardict[varname].VariableLabel or varname
def average_over_dictionary(mydict): """ Average over dictionary values. """ ave = sum([x for x in mydict.values()])/len(mydict) return ave
def bilinear_interpolation(n1, n2, n3, n4, x, y): """ Bilinear interpolation of value for point of interest (P). :param n1: value at node 1 :param n2: value at node 2 :param n3: value at node 3 :param n4: value at node 4 :param x: interpolation scale factor for x axis :param y: interpol...
def compare(lst1: list, lst2: list) -> list: """ Compares list's items to each other using OR operator. Saves the results of compairson to a new list and returns it. >>> compare([0, 0, 0], [1, 0, 1]) [1, 0, 1] >>> compare([0, 0, 0], [1, 1, 1]) [1, 1, 1] """ compared = [] fo...
def _get_lemma_from_mor(mor): """Extract lemma from ``mor``. Parameters ---------- mor : tuple(str, str, str) Returns ------- str """ lemma, _, _ = mor.partition("-") lemma, _, _ = lemma.partition("&") return lemma
def is_timefrequency_frequency(timefrequency): """return bool of whether input is TimefrequencyFrequency""" return isinstance(timefrequency, (int, float))
def data_override(parameter_data, override): """Override parameter values with specified values""" data=parameter_data for i in override: data[i]=override[i] return data
def find_boyer_moore(T, P): """Return the index of first occurance of P; otherwise, returns -1.""" n, m = len(T), len(P) if m == 0: return 0 last = {k: i for i, k in enumerate(P)} i = k = m - 1 while i < n: if T[i] == P[k]: if k == 0: return i ...
def sequence_sampling_probability(sequence_list): """Calculate genome size and the relative sizes of the the sequences in the multi-fasta file. Relative sizes are further used as probabilities for random sampling.""" # Calculate genome size genome_size = 0 for f in sequence_list: genome...
def _is_safe_type(value): """ These are types which aren't exploitable """ return ( isinstance(value, int) or isinstance(value, bool) or value is None )
def sub(keys, d): """ Create a new dict containing only a subset of the items of an existing dict. @param keys: An iterable of the keys which will be added (with values from C{d}) to the result. @param d: The existing L{dict} from which to copy items. @return: The new L{dict} with key...
def _sgn(x): """ Returns sign(x). :param x: Number :type x: float, int :return: 1, 0, -1 :rtype: int """ if x > 0: return 1 elif x == 0: return 0 else: return -1
def is_collection(name): """compare with https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/user""" return name in [ 'assignedLicenses', 'assignedPlans', 'businessPhones', 'imAddresses', 'interests', 'provisionedPlans', 'proxyAddresses', 'responsibilities', 's...
def get_file_extension(path): """returns the file extension of path""" if "." not in path: return "" else: return path.split(".")[-1].lower()
def simple2string(x): """ Simple objects (bytes, bool, float, int, None, str) are converted to string and returned. Other types are returned as None. """ if isinstance(x, bytes) or \ isinstance(x, bool ) or \ isinstance(x, float) or \ isinstance(x, int ) or \ x is N...
def nitro_tz(tz_id): """Maps McAfee SIEM/Nitro ESM internal timezone IDs to the tz database at: http://web.cs.ucla.edu/~eggert/tz/tz-link.htm Arguments: - `tz_id` (`int`): McAfee ESM internal timezone ID Returns: `str`: timezone name """ tz_map = { 1: "Pacific/Pago_Pa...
def purgewords(i): """ >>> purgewords("the agency of national trust buildings") 'buildings' """ purge = ["ltd", "limited", "company", "", "the", "of", "uk", "nhs", "pct", "foundation", "trust", "national", "department", "dept", "agency", "and", "association", "authority", "...
def _PureShape(shape): """Make sure shape does not contain int tensors by calling int().""" return [int(x) for x in shape]
def merge_strings(str1, str2, minimum_overlap): """ Returns a tuple `(m, i)` where `m` is a string that is the combination of str1 and str2 if they overlap, otherwise returns an empty string. The two strings are considered to overlap if they are non-empty and one of the following conditions apply: ...
def sign(x): """Calculates the sign of a number and returns 1 if positive -1 if negative 0 if zero should make it so type int or float of x is preserved in return type """ if x > 0.0: return 1.0 elif x < 0.0: return -1.0 else: return 0.0
def get_book_name(url): """ Gets the formated book name from the url E.g. http://www.wuxiaworld.com/desolate-era-index/de-book-24-chapter-29/ will return 'de-book-24' Arguments: A valid url Returns: A string """ book_list = str(url).split("/") for index, part ...
def receptive_field_size(total_layers, num_cycles, kernel_size, dilation=lambda x: 2**x): """Compute receptive field size Args: total_layers (int): total layers num_cycles (int): cycles kernel_size (int): kernel size dilation (lambda): lambda to compute d...
def get_terms_and_score_predictions_render(terms_and_score_predictions): """ From the full collection of terms and scores, select a number of terms and score predictions to render. :param terms_and_score_predictions: All terms and score predictions :return: List of the terms and scores to render ""...
def matches(s, t, i, j, k): """ Checks whether s[i:i + k] is equal to t[j:j + k]. We used a loop to ease the implementation in other languages. """ # tests if s[i:i + k] equals t[j:j + k] for d in range(k): if s[i + d] != t[j + d]: return False return True
def getTableSpaceString(tableSpace): """ Generates the TABLESPACE predicate of the SQL query. """ if tableSpace is not None and tableSpace != '': return " TABLESPACE " + tableSpace + " " else: return ""
def create_partition(elems, equiv_map): """Partition a collection of elements into buckets of equivalent elements. Two elements e1, e2 are considered equivalent if and only if equiv_map[(e1, e2)] == True. Returns the list of buckets and a mapping of elements to buckets. """ elem_to_bucket = {i: ...
def distinct(l): """ Given an iterable will return a list of all distinct values. """ return list(set(l))
def flattenDict(dict): """ Takes a dictionary with aggregated values and turns each value into a key with the aggregated key (from dict) as the corresponding value. """ flat_dict = {p: g for g, sublist in dict.items() for p in sublist} return flat_dict
def is_in_list(list_or_dict): """Checks to "seq" key is list or dictionary. If one seq is in the prefix-list, seq is a dictionary, if multiple seq, seq will be list of dictionaries. Convert to list if dictionary""" if isinstance(list_or_dict, list): make_list = list_or_dict else: ...
def _list(key: str, vals: dict) -> list: """Get a key from a dictionary of values and ensure it is a list.""" result = vals.get(key, []) if not isinstance(result, list): result = [result] return result
def clean_path(path): """Get name from path as last item without dot""" cleaned_name = path[path.rfind("/") + 1:] if "." in cleaned_name: cleaned_name = cleaned_name[:cleaned_name.rfind(".")] return cleaned_name
def reverse(string): """Reverses a string.""" return string[::-1]
def transform_mac_address_to_string_mac_address(string_mac_address): """ It transforms a MAC address from raw string format("\x00\x11\x22\x33\x44\x55") to a human readable string("00:11:22:33:44:55"). """ return ':'.join('%02x' % ord(b) for b in string_mac_address)
def fix_unclosed_quotations(summary_content): """ Merge unclosed quotations with previous sentences :param summary_content: summary text """ ix = 0 fixed_content = [] while ix < len(summary_content): sentence = summary_content[ix] if fixed_content and sum([True for ch in se...