content
stringlengths
42
6.51k
def calculate_mag(raw_val): """ Converts the raw value read from the magnetometer. Currently does not take calibration into consideration. """ result = raw_val * 2 / ((2**15) - 1) return result
def convert_c2f(c_in): """Convert the value in temp_data from Celsius to Fahrenheit and store the result in out-data.""" return (c_in * 1.8) + 32
def convert_to_eth(wei): """ Convert wei to eth :param wei: float, required :return: float """ eth = wei / 1000000000000000000 return eth
def count(s, sub, i = 0, last=None): """count(s, sub[, start[,end]]) -> int Return the number of occurrences of substring sub in string s[start:end]. Optional arguments start and end are interpreted as in slice notation. """ Slen = len(s) # cache this value, for speed if last is None: last = Slen elif las...
def with_dot(value): """ :param value: :return: """ return value & ~(1 << 7)
def _stringify(**parameters): """Converts query parameters to a query string.""" return "&".join([f"{k}={v}" for k, v in parameters.items() if v is not None])
def clean_response(response): """Remove a few info from the response before writing cassettes.""" remove_headers = {"Set-Cookie", "Date", "P3P"} if isinstance(response["headers"], dict): # Normal client stores headers as dict for header_name in remove_headers: response["headers"]...
def _is_array(data): """Return True if object implements all necessary attributes to be used as a numpy array. :param object data: Array-like object (numpy array, h5py dataset...) :return: boolean """ # add more required attribute if necessary for attr in ("shape", "dtype"): if not ...
def print_selected_post(choice, orderedArray): """" Function to format the results of search post """ vno = '' for posted in orderedArray: if posted[0] == choice: print('postID: ', posted[0]) print('postDate: ', posted[1]) print('pos...
def grouping2sql(column, recodedict): """ Takes a dict and transforms it to a SQL statement for recoding levels """ sql_when = ["case"] sql_when += [f"when {column} = '{index}' then '{level}'" for index,level in recodedict.items()] sql_when += ["else '-1' end"] sql_when = " ".join(sql_when) ...
def create_token_request_payload(auth_code, redirect_uri, optional_token_request_params): """ Construct payload for access token request """ token_request_payload = { # Don't include client_id param: Verizon doesn't like it 'grant_type': 'authorization_code', 'code': auth_code, ...
def _compute_position(input, index): """Compute line/column position given an index in a string.""" line = 1 col = 1 eol = None # last end of line character for c in input[:index]: if c == '\n' or c == '\r': if eol is None or eol == c: eol = c lin...
def str_to_bin(string): """ take a string and return a list of integers (1 or 0) representing that string in ASCII """ ret = list(string) # convert to binary representation ret = ['{:07b}'.format(ord(x)) for x in ret] # split the binary into ret = [[bit for bit in x] for x in ret] # ...
def value_to_str(x) -> str: """Convert value to string with suffix""" suffix = 'bytes' result = f'{x:.0f} {suffix}' if x >= 1024: x /= 1024 suffix = 'Kb' result = f'{x:.1f} {suffix}' return result
def split_global_comment(lines): """Split top comments into global and first glyph comment.""" while lines and not lines[-1]: lines = lines[:-1] try: splitter = lines[::-1].index('') except ValueError: global_comment = lines lines = [] else: global_comment = l...
def cremona_letter_code(n): """ Returns the Cremona letter code corresponding to an integer. For example, 0 - a 25 - z 26 - ba 51 - bz 52 - ca 53 - cb etc. .. note:: This is just the base 26 representation of n, where a=0, b=1, ..., z=25. This extends the old Cremona notation (counting f...
def process_phone(number): """ Process Phone Number for Printing (Currently works for USA Numbers) """ if len(number) == 12 and number[0:2] == '+1': return '+1(%s)%s-%s' % (number[2:5], number[5:8], number[8:12]) else: return number
def nombreLignes(source): """returns the number of line of the source file""" try: with open(source, "r", encoding="utf-8") as f: return len(f.readlines()) except IOError: print("Lecture du fichier", source, "impossible.") return 0
def filesafe(str_): """Convert a string to something safe for filenames.""" return "".join(c for c in str_ if c.isalnum() or c in (' ', '.', '_', '-')).rstrip()
def get_submodel_name(history = 60, lag = 365, num_neighbors = 20, margin_in_days = None, metric = "cos"): """Returns submodel name for a given setting of model parameters """ submodel_name = '{}-autoknn-hist{}-nbrs{}-margin{}-lag{}'.format(metric, ...
def trackOpposite(f_tr): """ DOCUMENT ME! """ l_d = f_tr + 180. while l_d >= 360.: l_d -= 360. # return return l_d
def fix_attributes(attrs): """ Normalise and clean up the attributes, and put them in a dict. """ result = {} for attr, value in attrs: attr = attr.lower() if value is None: result[attr] = True # The attribute is present, but has no value continue if ...
def underscore(s: str) -> str: """ Python packaging is very inconsistent. Even though this package's name is "chris_plugin", its _distribution's_ name might appear as "chris-plugin" in some situations but not all. e.g. when the plugin is installed via: `pip install -e ` ...
def identical(s1, s2): """ Verify that the nodes in {s1} and {s2} are identical. This has to be done carefully since we must avoid triggering __eq__ """ # for the pairs for n1, n2 in zip(s1, s2): # check them for _identity_, not _equality_ if n1 is not n2: return False # all ...
def make_compact(creation_sequence): """ Returns the creation sequence in a compact form that is the number of 'i's and 'd's alternating. Examples: [1,2,2,3] represents d,i,i,d,d,i,i,i. [3,1,2] represents d,d,d,i,d,d. Notice that the first number is the first vertex to be used fo...
def ensureList(x): """ If C{x} is a string, put it in a list, otherwise return the argument unchanged """ if isinstance(x, type('')): return [x] else: return x
def flip_bit(bit: str) -> str: """returns the input bit flipped""" assert bit == "0" or bit =="1" return "0" if bit =="1" else "1"
def iseven(x): """ Returns True if x is even Parameter x: The number to add to Precondition: x is an int """ return x % 2 == 0
def topological_sort_using_dfs(graph: list, vertices: int) -> list: """ Graph must be a DAG. No need to verify for existing elements Time complexity: O(V+E) Space complexity: O(V) """ def dfs(ind): nonlocal visited visited.add(ind) for vertex, connected in enumerate(gr...
def check_key_types(jsonObject, key, types): """ @brief check the dict key and type @param jsonObject The json object @param key The key @param types tuple of types @return True/False """ if not isinstance(jsonObject, dict): return False ...
def prune_none(data): """removes keys where the value is `None`, i.e. metrics which could not be computed""" return {k: v for k, v in data.items() if v is not None}
def score_mini_table(id, scores): """ Build the HTML table listing the Associated PGS. """ score_html = '' if scores: score_html += '<a class="toggle_btn" id="{}_scores"><i class="fa fa-plus-circle"></i></a>'.format(id) score_html += '<div class="toggle_content" id="list_{}_scores" style=...
def mix_arrays(a, b, factor): """Basic linear interpolation, factor from 0.0 to 1.0""" return a + max(min(factor, 1.0), 0.0) * (b - a)
def stringKeys(dictionary): """ Modifies the passed in dictionary to ensure all keys are string objects, converting them when necessary. """ for key, value in dictionary.items(): if type(key) != str: dictionary.pop(key) dictionary[str(key)] = value return diction...
def _ibabs_to_dict(o, fields, excludes=[]): """ Converts an iBabs SOAP response to a JSON serializable dict """ output = {} for f in fields.keys(): if f in excludes: continue v = getattr(o, f) if fields[f] is not None: if v is not None: ...
def knapsack_dp(capacity, weights, values): """ Function to find the max value capacity of a knapsack Args: capacity: max weight knapsack can carry weights: weight array of individual indexed item values: value associated with the items in same item order as weights Returns: ...
def check_if_neighbors_match(src_neighbor, trg_neighbor): """Check if any source and target neighbors match and return matches Args: src_neighbor (list): Source Neighbor List trg_neighbor (list): Target Neighbor List Returns: list: Matching of neighbors. """ matching = {} ...
def getPositions(mask): """ Get a list of positions where the specified mask has the bit set """ # XXX I don't exactly love this implementation, # but it works. binaryString = bin(mask)[2:] result = [] for index, c in enumerate(binaryString[::-1]): if int(c): resu...
def contains_no_complete_reductions(reductions): """Checks whether reductions contains a reduction with the empty word.""" for reduction in reductions: if reduction[-1] == "": return False return True
def LSTMCellWeightsShape(num_inputs, num_nodes): """Returns the shape of the weights for a single LSTM cell.""" # Dimension 0 accounts for combining x with the previous m state. # Dimension 1 accounts for the in value and the (in, forget, out) gates. return [num_inputs + num_nodes, 4 * num_nodes]
def tokenize_grapheme_langid(enhanced_word): """ tokenizer the langid of word (For multilingual GBERT) """ index_over = enhanced_word.index('}') lang_id = [enhanced_word[:index_over + 1]] return lang_id
def remcheck(val, range1, range2): """ Checks whether value is within range of two decimals. Parameters ---------- val : Float Value to be checked. range1 : Float Decimal 1. range2 : Float Decimal 2. Returns ------- bool Result of check. """...
def d_x_diffr_dy(x, y): """ derivative of d(x/r)/dy equivalent to second order derivatives dr_dyx :param x: :param y: :return: """ return -x*y / (x**2 + y**2)**(3/2.)
def array_diff(a, b): """Return the values in a that are not in b.""" tbr = [] for idx, number in enumerate(a): if number in b: tbr.append(idx) for idx in tbr[::-1]: a.pop(idx) return a
def _is_filepath(output_stream): """Returns True if output_stream is a file path.""" return isinstance(output_stream, str) and output_stream.startswith("file://")
def MIN(src_column): """ Builtin minimum aggregator for groupby Example: Get the minimum rating of each user. >>> sf.groupby("user", ... {'rating_min':tc.aggregate.MIN('rating')}) """ return ("__builtin__min__", [src_column])
def translate_alignment(align): """ Decodes an integer into a tuple for horizontal and vertical height :param align: alignment integer to decode """ h = v = 0 bits = (align & 0x38) >> 3 if bits & 0x4 == bits: v = 0x1 # top elif bits & 0x2 == bits: v = 0x10 # center elif bits & 0x1 == bits: ...
def factorial(n): """ Calculate n! Args: n(int): factorial to be computed Returns: n! """ if n == 0: return 1 # by definition of 0! return n * factorial(n-1)
def sort_table(matcher_type, matcher_map): """Returns the sorted html table for the given row map.""" table = '' for key in sorted(matcher_map.keys()): table += matcher_map[key] + '\n' return ('<!-- START_%(type)s_MATCHERS -->\n' + '%(table)s' + '<!--END_%(type)s_MATCHERS -->') % { ...
def get_threshold(max_ep, threshold): """ Returns actual threshold values based on: - Max EP - Threshold percentage """ return round(max_ep/100 * threshold)
def to_chr(x): """chr(x) if 0 < x < 128 ; unicode(x) if x > 127.""" return 0 < x < 128 and chr(x) or eval("u'\\u%d'" % x)
def _collection_spec(collection=None, revision=None) -> str: """ Return a template string for a collection/revision regular expression. Because both are optional in the ALF spec, None will match any (including absent), while an empty string will match absent. Parameters ---------- collecti...
def combineListResponces(responces): """Combines a list of device or datanode responces and returns the combined results.""" responces = [resp for resp in responces if resp is not None] items = [] for responce in responces: for item in responce.get("content", {}).get("items", []): i...
def tabulated_fibonacci(n): """Returns the nth fibonacci number Time complexity: O(n) Parameters ---------- n : int the nth fibonacci position Returns ------- int the nth fibonacci number ------- >>> tabulated_fibonacci(0) 0 >>> tabulated_fibonacci(1)...
def basename(file_name): """ Extract base name from file_name. `basename("test.e") -> "test"` """ fileParts = file_name.split(".") base_name = ".".join(fileParts[:-1]) return base_name
def shifted_list(l): """ Return the shifted (normalized) list of list l. A shifted/normalized is a list which starts with 0 and ends with last(l)-l[0] """ return [l[i] - l[0]+1 for i in range(len(l))]
def fill_kwargs(kwargs): """Give the kwargs dict default options.""" defaults = { "strandedness": None, "overlap": True, "how": None, "invert": None, "new_pos": None, "suffixes": ["_a", "_b"], "suffix": "_b", "sparse": { "self": False,...
def get_overlap_score(candidate, target): """Takes a candidate word and a target word and returns the overlap score between the two. Parameters ---------- candidate : str Candidate word whose overlap has to be detected. target : str Target word against which the overlap will be ...
def locate_min(a): """ Get list of indexes of all minimum value elements of a. :param a: Iterable :return: List of indexes """ smallest = min(a) return [index for index, element in enumerate(a) if smallest == element]
def mappingSightingPatternSTIX(etype): """ Map the patterns of stix 2.1 to threat sightings """ mapping = { "sha256": "file:hashes.'SHA-256'", "ipv4": "ipv4-addr:value", "domain": "domain-name:value", "url": "url:value", "dstHost": "domain-name:value", "md5": "file:hashes.md5", "sha1": "file:hashes...
def parse_cli_output(output): """ helper for testing parse the CLI --list output and return value of all set attributes as dict """ import re results = {} matches = re.findall(r"^(\w+)\s+.*\=\s+(.*)$", output, re.MULTILINE) for match in matches: results[match[0]] = match[1] retu...
def bboxMargin(a): """ box margin :param a: :return: """ return (a[2] - a[0]) + (a[3] - a[1])
def num_over_limit(n, limit): """ Returns the number of values for n C r that are greater than limit """ if n == 1: if 1 > limit: return 2 else: return 0 prod = 1 for r in range(n / 2 - 1): if prod > limit: return (n / 2 - r) * 2 + (n ...
def readPairInParen(string, startPos): """Reads a pair of numbers contained in parenthesis like this: (3413.55, 4103.456)""" # Find the bounds startParen = string.find('(', startPos) commaLoc = string.find(',', startParen) stopParen = string.find(')', commaLoc) # Extract the numbers...
def m(o, name, case_insensitive=True): """Returns the members of the object or dict, filtered by name.""" members = o.keys() if isinstance(o, dict) else dir(o) if case_insensitive: return [i for i in members if name.lower() in i.lower()] else: return [i for i in members if name in i]
def assert_axis_in_bounds(axis: int, ndim: int) -> int: """Assert a given value is inside the existing axes of the image. Returns ------- axis : int The axis which was checked for validity. ndim : int The dimensionality of the layer. Raises ------ ValueError The...
def valid_netbios_name(name): """Check whether a name is valid as a NetBIOS name. """ # See crh's book (1.4.1.1) if len(name) > 15: return False for x in name: if not x.isalnum() and not x in " !#$%&'()-.@^_{}~": return False return True
def average_lines(lines , Avg_ux , Avg_uy , Avg_lx , Avg_ly): """ - I will work on averaging the end points - ***************** we need to find better way to average the lines ****************** :param left_lanes: :param right_lanes: :return: """ # left lane averging end points avg_...
def longestPalindrome(s): """ :type s: str :rtype: str """ ## method-1 violence search, fail on (101/103) case : time limitation, time O(n^2) def sub_judge(start, end, len): if start > end: return len if start == end: return len + 1 if s[start] ==...
def islower(bb1, bb2): """ Returns true if obj 1 is lower than obj2. For obj 1 to be lower than obj 2: - The the top of its bounding box must be lower than the bottom of obj 2's bounding box """ _, bb1_max = bb1 bb2_min, _ = bb2 x1,y1,z1 = bb1_max x2,y...
def is_feasible(params, test_fixtures): """ Checks if the specified parameter and test fixture combination is feasible. A combination is feasible if none of the test fixture resources appear in the parameters and if all of the exclusive-use test fixture resources are only used by one test fixture. ...
def check_month(month_number, month_list): """ Check if a month (as integer) is in a list of selected months (as strings). Args: month_number: The number of the month. month_list: A list of months as defined by the configuration. Returns: Bool. """ month_map = { ...
def key_with_max_val(d): """ a) create a list of the dict's keys and values; b) return the key with the max value """ v = list(d.values()) k = list(d) return k[v.index(max(v))]
def mix_probability_to_independent_component_probability(mix_probability: float, n: float) -> float: """Converts the probability of applying a full mixing channel to independent component probabilities. If each component is applied independently with the returned component probability, the overall effect i...
def test_path_and_query_parameters( arg1, arg2, ): """ Use same arg name as the one in path for receiving path args For those args which names not matched path arg names, will be parsed as query parameter ```python from django_mini_fastapi import Path @api.get('/test_path_and_query_par...
def dispatch_across_consumers(products, consumers, rank, even=False): """Dispatch products across all consumers. Args: products: number of products to be dispatched. consumers: number of consumers. rank: rank of this consumer in all consumers. even: dispatch across consumers evenly if Tru...
def _IsExtraneousLine(line, send_cmd): """Determine if a line read from stdout in persistent shell is extraneous. The results output to stdout by the persistent shell process (in PersistentShell below) often include "extraneous" lines that are not part of the output of the shell command. These "extraneous" lin...
def calculate_score(s1, s2, l1, l2, startpoint): """calculate alignment scores""" matched = "" # to hold string displaying alignements score = 0 for i in range(l2): # import ipdb; ipdb.set_trace() ## debug breakpoint added if (i + startpoint) < l1: if s1[i + startpoint] == s2[i]: #...
def valueForKeyPath(dict, keypath, default = None): """ Get the keypath value of the specified dictionary. """ keys = keypath.split('.') for key in keys: if key not in dict: return default dict = dict[key] return dict
def get_dataset_json(met, version): """Generated HySDS dataset JSON from met JSON.""" return { "version": version, "label": met['data_product_name'], "starttime": met['sensingStart'], "endtime": met['sensingStop'], }
def is_span(node: dict) -> bool: """Check whether a node is a span node.""" return node.get('_type', '') == 'span' or isinstance(node, str) or hasattr(node, 'marks')
def format_size(size): """ Return a human-readable value for the `size` int or float. For example: >>> assert format_size(0) == '0 Byte' >>> assert format_size(1) == '1 Byte' >>> assert format_size(0.123) == '0.1 Byte' >>> assert format_size(123) == '123 Bytes' >>> assert format_size(10...
def pp(n, p, l, t): """calculate pp,qq for SBM given p from ER p : p from G(n,p) l : # of communities t : ratio of pp/qq """ pp = p * n * (n - 1) / (n ** 2 / l - n + t * n ** 2 * (l - 1) / l) qq = t * pp return pp, qq
def case_convert(snakecase_string: str) -> str: """Converts snake case string to pascal string Args: snakecase_string (str): snakecase string Returns: str: Pascal string """ return snakecase_string.replace("_", " ").title().replace("Cnn", "CNN")
def mergesort(items): """Sort an input list array. Args: items: A list of ints to be sorted from least to greatest Returns: merged: A list of sorted ints """ if len(items) <= 1: return items mid = len(items) // 2 left = items[:mid] right = items[mid:] left...
def delist_arguments(args): """ Takes a dictionary, 'args' and de-lists any single-item lists then returns the resulting dictionary. In other words, {'foo': ['bar']} would become {'foo': 'bar'} """ for arg, value in args.items(): if len(value) == 1: args[arg] = value[0] ...
def cocktail_shaker_sort(unsorted): """ Pure implementation of the cocktail shaker sort algorithm in Python. """ for i in range(len(unsorted)-1, 0, -1): swapped = False for j in range(i, 0, -1): if unsorted[j] < unsorted[j-1]: unsorted[j], unsorted[j-...
def count_negatives(nums): """Return the number of negative numbers in the given list. >>> count_negatives([5, -1, -2, 0, 3]) 2 """ nums.append(0) # We could also have used the list.sort() method, which modifies a list, putting it in sorted order. nums = sorted(nums) return nums.index(0...
def create_stairwaytotravel_url(place_id): """Create a url to a place page given the place id.""" return "https://stairwaytotravel.com/explore/" + str(place_id)
def merge_population(population): """ create a merged population representation """ return population["feasible"] + population["infeasible"]
def hash_int_pair(ind1, ind2): """Hash an int pair. Args: ind1: int1. ind2: int2. Returns: hash_index: the hash index. """ assert ind1 <= ind2 return ind1 * 2147483647 + ind2
def _auth_callback(userid, request): """ Get permissions for a userid """ return ['default']
def non_negative_validation(value): """ Validate if value is negative and raise Validation error """ if isinstance(value, list): if any(v < 0 for v in value): raise ValueError("The Values in the list must not be negative") else: return value else: if ...
def _align_token_list(text, token_list, char_offset=0): """Align list of string tokens to text and return list of Token objects.""" token_spans = [] for text_token in token_list: start = text.index(text_token, char_offset) token_spans.append((start, start + len(text_token))) char_off...
def cria_posicao(col, ln): # str x str -> posicao """ Recebe duas cadeias de carateres correspondentes a coluna c e a linha l de uma posicao e devolve a posicao correspondente, se ambos os argumentos forem validos. :param col: Coluna, pode ser 'a', 'b' ou 'c' :param ln: Linha, pode ser '1', '2'...
def normal2SD(x,y,z): """Converts a normal vector to a plane (given as x,y,z) to a strike and dip of the plane using the Right-Hand-Rule. Input: x: The x-component of the normal vector y: The y-component of the normal vector z: The z-component of the normal vector Output: ...
def process_group(grp): """ Given a set of instructions, with commands `acc`, `jmp`, or `nop` and values as some ints, it is known that if executed, it falls in an infinite loop. Compute the accumulated value just before it falls into recursion. :return accumulator, i: The accumulated ...
def quick_clean(raw_str): """ args: - raw_str: a string to be quickly cleaned return - the original string w/ all quotes replaced as double quotes """ return raw_str.replace("''", '" ').replace("``", '" ')
def get_border_bounding_rect(h, w, p1, p2, r): """Get a valid bounding rect in the image with border of specific size. # Arguments h: image max height. w: image max width. p1: start point of rect. p2: end point of rect. r: border radius. # Returns rect coord ...
def sort_big_file(lines): """ 10.6 Sort Big File: Imagine you have a 20 GB file with one string per line. Explain how you would sort the file. Solution: bucket sort, we make a pass through each line and copy it at the an of new file that starts with the first two letters of the line. At the end we...