content
stringlengths
42
6.51k
def parse_type_inner(text, start_tok='[', end_tok=']'): """ Returns the inner type of a generic type. Example: List[any] => any :param text: type text to parse :param start_tok: type opening token :param end_tok: type end token :return: Inner type """ level = 0 start = None f...
def _generate_gray_code(num_bits): """Generate the gray code for ``num_bits`` bits.""" if num_bits <= 0: raise ValueError('Cannot generate the gray code for less than 1 bit.') result = [0] for i in range(num_bits): result += [x + 2**i for x in reversed(result)] return [format(x, '0%s...
def __subi_rd_i(op): """ Return Rd and immediate parts from a SUBI opcode. """ AVR_SUBI_RD_MASK = 0x00F0 AVR_SUBI_CONST_MASK = 0x0F0F imm_part = op & AVR_SUBI_CONST_MASK imm = ((imm_part >> 4) & 0xF0) | (imm_part & 0xF) # rd_part is 4 bits and indicates 16 <= Rd <= 31 rd_part = (op...
def _eq(x, y): """ Tests a pair of strings for equivalence by attempting to convert them to floats and falling back to string comparison. :param x: string :type x: str :param y: string :type y: str :return: boolean :rtype: bool """ try: return float(x) == float(y) ...
def check_if_represents_int(s): """Checks if the string/bytes-like object/number s represents an int""" try: int(s) return True except ValueError: return False
def non_strict_conj(a, b): """Non-strict conjunction Arguments: - `a`: a boolean - `b`: a boolean """ if a == False: return False elif b == False: return False elif a == True and b == True: return True else: return None
def _parse_ps_output(string): """parse `ps -p <pid> -o etime` output and return total seconds count""" t = string.replace('-', ':').split(':') t = [0] * (4 - len(t)) + [int(i) for i in t] seconds = t[0] * 86400 + t[1] * 3600 + t[2] * 60 + t[3] return seconds
def relativeSequence(wireSequence, initialSequence, lapNumber): """ Compute a relative sequence number from a wire sequence number so that we can use natural Python comparisons on it, such as <, >, ==. @param wireSequence: the sequence number received on the wire. @param initialSequence: the ISN for t...
def iou(bbox1, bbox2): """ bbox1: [x1, y1, x2, y2] bbox2: [x1, y1, x2, y2] """ xx1 = max(bbox1[0], bbox2[0]) yy1 = max(bbox1[1], bbox2[1]) xx2 = min(bbox1[2], bbox2[2]) yy2 = min(bbox1[3], bbox2[3]) interArea = max(0, xx2 - xx1) * max(0, yy2 - yy1) bbox1_area = (bbox1[2] - bbox1...
def inverse(x): """ Inverse 0/1 variable Args: x: variable with float32 dtype Returns: inverse_x: variable with float32 dtype """ inverse_x = -1.0 * x + 1.0 return inverse_x
def is_numeric(s): """Check if input string is a numeric. :param s: String to check. :return: True if input is a numeric. False if empty or not a numeric. """ try: int(s) return True except (TypeError, ValueError): return False
def slice_polar_coords(dist, angles, dist_range, angle_range): """ Returns a subset of pixel radial distances and angles, such that any pixel's radial distance and angle fall within specified range :param dist: list of pixel radial distances :param angles: list of corresponding pixel angles in degrees ...
def _convert_num(s): """Convert a numeric string to a number. Args: s (str): A number representing a string Returns: int or float: The numeric representation of the string """ try: return int(s) except ValueError: return float(s)
def zero_times(recognitions): """Set times to zero so they can be easily compared in assertions""" for recognition in recognitions: recognition.recognize_seconds = 0 return recognitions
def does_contain_consecutive_underscores(name: str) -> bool: """ Checks if variable contains consecutive underscores in middle of name. >>> does_contain_consecutive_underscores('name') False >>> does_contain_consecutive_underscores('__magic__') False >>> does_contain_consecutive_underscor...
def checkData(data): """ Check if Data is in a healthy state """ try: toplevel = data.keys() for key in ['version', 'nodes', 'updated_at']: if key not in toplevel: print("Missing key " + key) return False return True except KeyE...
def convert_string_to_bcd(string=""): """Convert the string to BCD array >>> vals = "89860009191190000108" >>> convert_string_to_bcd(vals) [0x98, 0x68, 0x00, 0x90, 0x91, 0x11, 0x09, 0x00, 0x10, 0x80] """ ret_len = int(len(string)/2) if (len(string) % 2) == 0...
def expand_shape(seq, l, fill_value=None): """Expand a sequence with a fill value """ seq = tuple(seq) if len(seq) > l: return seq seq = ((l - len(seq)) * (fill_value,)) + seq return seq
def dict_delta(dict_a, dict_b): """ recursively compares two dictionaries, returns the dictionary of differences. aka retval = dict_b - dict_a """ result = dict() for k in dict_b: if k in dict_a: if isinstance(dict_a[k], dict) and isinstance(dict_b[k], dict): ...
def has_message_body(status): """ According to the following RFC message body and length SHOULD NOT be included in responses status 1XX, 204 and 304. https://tools.ietf.org/html/rfc2616#section-4.4 https://tools.ietf.org/html/rfc2616#section-4.3 """ return status not in (204, 304) and...
def emf(fbexp, ep_exp): """ Calculate the void fraction at minimum fluidization for the specified bed. Parameters ---------- fbexp : float Bed expansion factor [-] ep_exp : float Void fraction in the expanded bed [-] Returns ------- e_mf : float Void fractio...
def title_case(sentence): """ Converts enetered string into the title_case Parameters ----------- sentence : string string to be converted into sentence case Returns ------- title_case_sentence : string string in TITLE CASE Example ------- >>>title_case('Th...
def find_longest_repeat(seq): """Find the longest repeat in a string, then return the length and the character in a tuple. """ maximum = 0 count = 0 current = '' letter = '' for nt in seq: if nt == current: count += 1 else: count = 1 ...
def calculate_num_param_n_num_flops(conv_d): """ calculate num_param and num_flops from conv_d """ n_param = 0 n_flops = 0 for k in conv_d: #i:(inp_idx, out_idx, inp_shape, out_shape, kernel_shape) inp_shape, out_shape, kernel_shape = conv_d[k][2],conv_d[k][3],conv_d[k][4] ...
def create_image_markdown(filename): """ Create a valid markdown string that presents the image given as a filename """ text = "![]({0})".format(filename) return text
def ast(a, b, func): """ return string of instructions that excute assert function. a: str,int,D,I value0 b: str,int,D,I value1 func: int 0x01 a > b 0x02 a = b 0x03 a < b """ return """ MOV 0xFD, {} MOV 0xFE, {} MOV 0xF...
def ss(inlist): """ Squares each value in the passed list, adds up these squares and returns the result. Usage: lss(inlist) """ ss = 0 for item in inlist: ss = ss + item * item return ss
def remove_overlap(ranges): """ Simplify a list of ranges; I got it from https://codereview.stackexchange.com/questions/21307/consolidate-list-of-ranges-that-overlap """ result = [] current_start = -1 current_stop = -1 for start, stop in sorted(ranges): if start > current_stop: # this segment starts after t...
def guessShaper(key, layer): """ uses the name to find a known shaper otherwise uses the default, up sample. Possibly not used if the output size is the desired depth. """ kl = key.lower() if "crop" in kl: return "crop" return "upsample"
def reverse_dict(adict): """Return the reverse mapping of a dictionary.""" return dict([(v, k) for k, v in adict.items()])
def parse_voice_flags(flags): """Parses flags and returns a dict that represents voice playing state.""" # flags: [0-9]{8} if flags[0] == '0': return {'voice': 'stop'} else: return {'voice': { 'number': int(flags[1:3]), 'repeat': int(flags[4:6]) }}
def select_keys(keys: list, m: dict): """ Selects specific keys in a map :param keys: Keys to select :param m: map to filter :return: map """ new_map = {} for key, value in m.items(): if key in keys: new_map[key] = value return new_map
def LimiterG1forHYU(dU1, dU2): """Return the limiter for Harten-Yee Upwind TVD limiter function. This limiter is further used to calculate the modified flux limiter function given by Equation 6-131. Calculated using Equation 6-132 in CFD Vol. 1 by Hoffmann. """ if dU2 != 0: S = ...
def unescape_latex_entities(text): """Limit ourselves as this is only used for maths stuff.""" out = text out = out.replace('\\&', '&') return out
def merge_sort(collection): """ Pure implementation of the merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3,...
def _get_value(value): """Interpret null values and return ``None``. Return a list if the value contains a comma. """ if not value or value in ['', '.', 'NA']: return None if ',' in value: return value.split(',') return value
def get_end_point(starting_point, direction_distance): """ Helper to compute endpoint from starting point and direction >>> get_end_point((1, 2), 'L1') (0, 2) >>> get_end_point((3, 4), 'R2') (5, 4) >>> get_end_point((5, 6), 'D3') (5, 3) >>> get_end_point((6, 7), 'U4') (6, 11) ...
def get_codepage(locale_name): """Extract codepage from the locale name. """ # extract codepage codepage_sep = locale_name.rfind('.') if codepage_sep == -1: codepage = "0" else: codepage = locale_name[codepage_sep + 1:] # if less than 4 bytes prefix with a zero if len(cod...
def _H4(x): """Fourth Hermite polynomial.""" return (4 * x**4 - 12 * x**2 + 3) * 24**-0.5
def run_program(program): """Run a program, halting when an instruction is executed a second time :returns: (accumulator, ran_whole_program) """ accumulator = 0 visited_instructions = set() i = 0 while i not in visited_instructions and i < len(program): visited_instructions.add(i) ...
def convertTimeStringToTime(timeStr): """ We assume the timeStr has the format [hh:mm:ss.ssss] Returns -1.0 if conversion fails, otherwise time as a float """ # noinspection PyBroadException try: if timeStr[0] != '[': return -1.0 if timeStr[-1] != ']': re...
def reduce_nest(nested_arrays): """ Returns a 1D list of data Arguments: nested_arrays ([[int]]): The 2D array of integers to reduce """ count, sum = 0, 0 for array in nested_arrays: # reduces nested arrays of different size into one float for value in array: sum += value count += 1 if count > 0...
def mask2cidr(mask): """Get cidr number bits from netmask. """ try: return sum([bin(int(x)).count("1") for x in mask.split(".")]) except Exception: return 24
def ll_assert_not_none(x): """assert x is not None""" assert x is not None, "ll_assert_not_none(%r)" % (x,) return x
def strip_suffix(string, suffix): """Remove a suffix from a string if it exists.""" if string.endswith(suffix): return string[:-(len(suffix))] return string
def _asTruecolorString(rgb): """ Encode the given color as a Truecolor string Parameters: rgb (tuple): a tuple containing Red, Green and Blue information Returns: The encoded string """ return "2;{};{};{}".format(rgb[0], rgb[1], rgb[2])
def _FilterTestsUsingPrefixes(all_tests, pre=False, manual=False): """Removes tests with disabled prefixes. Args: all_tests: List of tests to filter. pre: If True, include tests with PRE_ prefix. manual: If True, include tests with MANUAL_ prefix. Returns: List of tests remaining. """ filter...
def _gt(field, value, document): """ Returns True if the value of a document field is greater than a given value """ try: return document.get(field, None) > value except TypeError: # pragma: no cover Python < 3.0 return False
def determine_name(func): """ Given a function, returns the name of the function. Ex:: from random import choice determine_name(choice) # Returns 'choice' Args: func (callable): The callable Returns: str: Name string """ if hasattr(func, "__name__"): ...
def red_blue_cmap(x): """Red to Blue color map Args: x (float): value between -1 ~ 1, represents normalized saliency score Returns (tuple): tuple of 3 float values representing R, G, B. """ if x > 0: # Red for positive value # x=0 -> 1, 1, 1 (white) # x=1 -> 1, 0, 0...
def runlength(blk, p0, p1): """ p0 is the source position, p1 is the dest position Return the length of run of common chars """ for i in range(1, len(blk) - p1): if blk[p0:p0+i] != blk[p1:p1+i]: return i - 1 return len(blk) - p1 - 1
def influence_reward(agent, world): """ influence-based reward, directional reference: https://arxiv.org/pdf/1810.08647.pdf """ rew = 0 return rew
def is_anti_meridian(es_json): """ Checking here if the polygon crosses the time meridian If so then correct it :param es_json: :return: """ positive = 0 negative = 0 for coord in es_json["coordinates"][0]: if float(coord[0]) < 0: negative += 1 else: ...
def normalize_headers(headers): """ Create a dictionary of headers from: * A list of curl-style headers * None * a dictionary (return a *copy*). :param headers: List or dict of header (may also be None). :type headers: Iterable[string] | dict[string, string] | None :return: A d...
def are_bools(tuple_arg): """ are_bools --------- - Param: tuple_arg. Tuple, required. - Returns: bool. True if all items in tuple_arg are booleans. False otherwise. """ if type(tuple_arg) != tuple: raise TypeError( "Class type not supported; tuple expected." ...
def parse_exit(ec): """ Parses an exit code any way possible Returns a string that shows what went wrong """ if (ec & 127) > 0: my_signo = ec & 127 my_core = "" if (ec & 128) == 128: my_core = " (core)" my_result = "died on signal {}{}".format(my_signo, my...
def __key2str(key): """ Take a key and return in string format. """ if type(key) is tuple: return " ".join(key) else: return key
def lowercase_keys(input_dict): """ Take input and if a dictionary, return version with keys all lowercase """ if not isinstance(input_dict,dict): return input_dict safe = dict() for key,value in input_dict.items(): safe[str(key).lower()] = value return safe
def extract_url(url): """Creates a short version of the URL to work with. Also returns None if its not a valid adress. Args: url (str): The long version of the URL to shorten Returns: str: The short version of the URL """ if url.find("www.amazon.de") != -1: index = ...
def location(loc): """Function to format location""" if loc == 'None': return {'parsed' : 'None', 'string' : 'N/A'} return {'parsed' : loc, 'string' : loc}
def create_mac_string(num, splitter=':'): """Return the mac address interpretation of num, in the form eg '00:11:22:33:AA:BB'. :param num: a 48-bit integer (eg from uuid.getnode) :param spliiter: a string to join the hex pairs with """ mac = hex(num)[2:] # trim trailing L for long consts ...
def elapsed_time(variable, time_stamp): """ Simplifies the time axis, by subtracting the initial time. This is useful because usually the time stamps are given in a long format (i.e. in the order of 1e9) :param variable: Reference variable to obtain the size of the time array :param time_stamp: The ...
def combine_to_id64(system, body): """ Combines a system ID64 and body ID to create an ID64 representing that body Args: system: An ID64 representing a system body: A zero-indexed body ID Returns: A combined ID64 representing the specified body within the specified system """ return (system & (...
def _longest_match(deltas): """Find the matching pair of values in the deltas array with the largest difference in indices. Returns tuple (lo, hi), not inclusive of hi """ _map = {0: -1} # seed distance zero at index -1 res = None for index, d in enumerate(deltas): if d in...
def in_scope(repository_data): """Return whether the given repository is in scope for the configuration. Keyword arguments: repository_data -- data for the repository """ if "scope" in repository_data["configuration"] and repository_data["configuration"]["scope"] == "all": return True ...
def b(i, j): """Block coordinates""" return [(i, j), (i, j+1), (i+1, j), (i+1, j+1)]
def search_unordered_list(number_list): """ Search a given list for the largest number """ largest_number = 0 for num in number_list: if num > largest_number: largest_number = num else: pass print( "{} at position {} is the largest number".format...
def _almost_flatten(metrics): """Turn a nested list (e.g. ['foo', ['bar', 'baz', ['tor, 'tar']]] into a flattened list of names anchored at the first element: [["foo", "bar", "baz", "tor"], ["foo", "bar", "baz", "tar"]] Two notes for posterity.: This does extra work, recursinge too often. Als...
def is_end_word(word): """ Determines if a word is at the end of a sentence. """ if word == 'Mr.' or word == 'Mrs.': return False punctuation = "!?." return word[-1] in punctuation
def _hyphen_to_camel(s): """Convert a string like ``root-device-type`` to ``RootDeviceType``""" return ''.join(part[0].upper() + part[1:] for part in s.split('-'))
def AsSortedList(return_value): """Converts any iterable into a sorted Python list.""" return list(sorted(return_value))
def _canonicalize_units(units): """ Standardized units to a lower case representation. Args: units: A list of strings Returns: A dictionary that maps a lower case unit to its corresponding unit. """ unit_dict = {} for unit in units: unit_dict[unit.lowe...
def lookup_ip_country(address, database): """Returns the country code for a given ip address.""" info = database.get(address) try: return info['country']['iso_code'] except Exception: return ''
def escape_json_for_html(value): """ Escapes valid JSON for use in HTML, e.g. convert single quote to HTML character entity """ return value.replace("'", "&#39;")
def get_cookies_from_headers(headers): """Get cookies dict from headers' Set-Cookie""" cookies = {} cookie_list = None for k, v in headers.items(): if k.lower() == 'set-cookie': cookie_list = headers[k].split('\n') if cookie_list: for line in cookie_list: for...
def insertion_sort(list): """ Complexity: Worst case O(N^2) when sorted backwards Best Case O(N) when sorted """ for i in range(1,len(list)): tmp = list[i] j = i - 1 while j >= 0 and list[j] > tmp: list[j+1] = list[j] j -= 1 list[j+1] = tmp...
def create_headers(config): """Create headers for github api request.""" return { 'Accept': 'application/vnd.github.v3+json', 'Authorization': 'token {}'.format(config['auth_token']), 'Content-Type': 'application/json', 'User-Agent': config['user_agent_string'] }
def remove_out_of_domain (l): """ Remove list element that value < 0 or value > 255 :param l: list <number> :returns: list """ new_list = l.copy() for i in range(len(l)): if l[i] > 255 or l[i] < 0: new_list.remove(l[i]) return new_list
def cleanup(text): """ Validates that the given text is clean: only contains [0-9a-zA-Z_] """ # if not REGEX_ALPHANUMERIC.match(text): # raise SyntaxError('invalid table or field name: %s' % text) return text
def diff_json(local, other): """ Calculates the difference between two JSON documents. All resulting changes are relative to @a local. Returns diff formatted in form of extended JSON Patch (see IETF draft). via: https://bitbucket.org/vadim_semenov/json_tools/src/75cc15381188c760bad...
def long_to_ip (l): """ Convert 32-bit integerto to a ip address. """ return '%d.%d.%d.%d' % (l>>24 & 255, l>>16 & 255, l>>8 & 255, l & 255)
def add_zeros(card): """ This adds leading zeros to the card number display. """ return str(['000' if card < 100 else '00'][0]) + str(card)[-5:]
def map_to_parent(stop_id, stop_info): """ Given a stop ID and the stop Info dict, map to the parent station, unless there isnt one.""" # NOTE: Currently this is disabled to keep LA Metro working until # I figure something else out. return stop_id
def _ith_in_node(worker_id, worker_num_dict): """ .. code-block: python >>> worker_num_dict = {('node0', 10000): 0, ('node0', 10001): 1, ('node1', 10000): 2, ('node0', 10002): 3} >>> _ith_in_node(('node0', 10002), worker_num_dict) 2 >>> _ith_in_node(('node1', 10000), worker_num_d...
def is_float(string): """Check if a string can be converted to a non-zero float. Parameters ---------- string : str The string to check for convertibility. Returns ------- bool True if the string can be converted, False if it cannot. """ try: return True if ...
def dataAttribute2Html5Attribute(key): """The @dataAttribute2Html5Attribute@ method converts an *key* attribute that starts with `'data_'` to the HTML5 attribute that starts with `'data-'`. Otherwise the *key* attribute is answered unchanged. """ if key.startswith(u'data_'): return 'data-' +...
def pproc_command(commands): """ Creates a pproc command from a list of command strings. """ commands = " ".join([ "\"{}\"".format(command) for command in commands ]) return "pproc {}".format(commands)
def fix_blockname(name): """Fixes blanks in 4th column of block names, caused by TOUGH2 treating names as (a3, i2)""" if name[2].isdigit() and name[4].isdigit() and name[3] == ' ': return '0'.join((name[0:3], name[4:5])) else: return name
def deci_deg_to_hr_min_sec(deci_deg): """assume deci_deg +ve""" deci_hours = deci_deg/15. schminutes,schmeconds = divmod(deci_hours*3600,60) hours,schminutes = divmod(schminutes,60) return (hours,schminutes,schmeconds)
def findFirstOcc(array, contents, startBool=False): """ Finds the first occurunce in contents of any one of the elements in array and returns where that occurunce is :param array: List that we want to find where the first occurunce of any one of the elements in the list is :param contents: String that w...
def getAllowedTotalSpins( L, S, useFactor2Trick=True ): """ Returns a list of allowed J values from summing angular momenta L and S, where :math:`\\vec{J}=\\vec{L}+\\vec{S}` which implies :math:`|L-S| \\leq J \\leq L+S` The useFactor2Trick flag tells the routine whether we are summing real angular ...
def rel_error(deriv, orig): """ Relative Error. Calculating the relative error after approximating the derivative. Parameters: deriv : approximation orig : actual value Returns: Relative Error """ return abs(orig - deriv) / abs(orig)
def get_presentation_attributes(filename): """ Parses the given video-filename and determines the type of presentation (real or attack), the quality (laptop or mobile), and in case of attack, the instrument used (video_hd, video_mobile, or print) Returns: presentation: a string either 'real' or...
def _get_node_text(text): """Cast text to a unicode string to handle unicode characters. Keyword arguments: text --- the string to cast to unicode """ if text: return _unicode(text) else: return ""
def intable(int_str, base=10): """Safely check if a string is convertible to int. :param str int_str: the string to convert into int. :returns: True if the string is convertible, False if not. """ try: int(int_str, base) return True except: return False
def remove_extra_space( text: str, ) -> str: """To remove extra space in a given text. Parameters ---------- text : str The text to clean. Returns ------- str returns text after removing all redundant spaces. Examples -------- >>> from SkillNer.cleaner impo...
def combine_xml_points(seq, units, handle_units): """Combine multiple Point tags into an array.""" ret = {} for item in seq: for key, value in item.items(): ret.setdefault(key, []).append(value) for key, value in ret.items(): if key != 'date': ret[key] = handle_u...
def get_labels(arg_labels): """ Return list of tuples representing key-value label pairs. """ labels = [] if arg_labels: pairs = arg_labels.split(",") for pair in pairs: kv = pair.split("=") if len(kv) == 2: labels.append((kv[0], kv[1])) el...
def find_max_where(predicate, prec=1e-5, initial_guess=1, fail_bound=1e38): """Find the largest value for which a predicate is true, along a half-line. 0 is assumed to be the lower bound.""" # {{{ establish bracket mag = initial_guess if predicate(mag): mag *= 2 while predicate(ma...
def normalize_command_name(command_name): """ Normalises the given command name. Parameters ---------- command_name : `str` The command name to normalize. """ return command_name.lower().replace('_', '-')