content
stringlengths
42
6.51k
def normalize_scalar(value: int) -> str: """ 5.1.1.4 - c.1: Scalar values shall be rendered using their hexadecimal representation. """ return "%x" % value
def f_ok(a, b): """Function f Parameters ---------- a : int Parameter a b : float Parameter b Returns ------- c : list Parameter c """ c = a + b return c
def match_substring(elements_list: list, match_pattern: str) -> list: """ Return indexes of a list that matches with pattern. Similar to MATLAB find function """ indexes = [i for i in range(len(elements_list)) if match_pattern in elements_list[i]] return indexes
def isOdd(x): """ Define if a number is odd :param x: x a number :return: true is x is an odd number """ return x % 2 == 1
def to_bool(value): """Converts 'something' to boolean. Raises exception for invalid formats Possible True values: 1, True, "1", "TRue", "yes", "y", "t" Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...""" if value is None: return False if str(value)....
def _shell_escape(string): """ Escape double quotes, backticks and dollar signs in given ``string``. For example:: >>> _shell_escape('abc$') 'abc\\\\$' >>> _shell_escape('"') '\\\\"' """ for char in ('"', '$', '`'): string = string.replace(char, '\%s' % char...
def _quote(filename, protect = "="): """Quote the filename, by escaping = by \\= and \\ by \\\\""" return filename.replace("\\", "\\\\").replace(protect, "\\" + protect)
def normalize_rate(rate: float) -> float: """ normalize rate to unit :param rate: :return: """ if rate > 100: raise Exception("Invalid interest rate") return rate / 100 if rate > 0.5 else rate
def get_outputportnum(port): """ Get the output port number corresponding to the port letter """ portnum = { 'a': 0, 'b': 1, 'c': 2, 'd': 3 } port = port.lower() if type(port) is not str: raise NameError('Invalid output port.') if port not in list(portnu...
def is_clean_packet(packet): # pragma: no cover """ Returns whether or not the parsed packet is valid or not. Checks that both the src and dest ports are integers. Checks that src and dest IPs are valid address formats. Checks that packet data is hex. Returns True if all tests pass, False other...
def rename_record_columns(records, columns_to_rename): """ Renames columns for better desc and to match Socrata column names :param records: list - List of record dicts :param columns_to_rename: dict - Dict of Hasura columns and matching Socrata columns """ for record in records: for col...
def minmax(dates): """Returns an iso8601 daterange string that represents the min and max datemap.values(). Args: datestrings: [d1, d2, d3,] Returns: ['min_date/max_date',] Example: >>> minmax(['2008-01-01', '2010-01-01', '2009-01-01']) "2008-01-01/2010-01-01" ...
def RK4(f, y, t, h): """ One step of the numerical solution to the DE (dy/dt = f). :param f: Time-derivative of y :param y: Previous value of y, used in finding the next :param t: Time :param h: Time-step length :return: Value of y at time t+h """ k1 = h*f(t,y) ...
def truncate_comics(comics): """Truncate the list of comics based on (hardcoded) criterias. On the long run, I'd like the criteria to be provided via command-line arguments.""" limit = 3000 len_comics = len(comics) if len_comics > limit: print("Keeping %d comics out of %d" % (limit, len...
def get_aligned_sequences(mafft_output): """ Parse aligned FASTA sequences from MAFFT output. :param mafft_output: MAFFT program output in FASTA format :return: Array of the aligned sequences in FASTA format """ # mafft_lines = Array of FASTA lines mafft_lines = mafft_output.splitlines() ...
def bubble_sort(lst=[]): """Bubble sort.""" for i in range(len(lst) - 1): for j in range(len(lst) - 1): if lst[j] > lst[j + 1]: lst[j], lst[j + 1] = lst[j + 1], lst[j] return lst
def is_none(param: str) -> bool: """Returns True if parameter is none""" values = ["", "none"] if str(param).lower() in values: return True else: return False
def _join(words): """Join words into single line. Args: words: List of words. Returns: String with space separated words. """ return u' '.join(words) if words else u''
def tuple_to_str(my_tuple, delimiter=''): """ Semantics: Convert tuples to strings. Args: my_tuple: a tuple to be converted into a string delimiter: tuple[0] + delimiter + tuple[1] + delimiter + ... Returns: returns the converted string. """ my_str = '' fo...
def is_internet(ip): """ judge if the ip belongs to intranet :ip : format xxx.xxx.xx.xx : return: True/False """ # todo: judge if match the format ip = ip.split(".") ip = [int(_) for _ in ip] # print ip if (ip[0]) == 10: return False elif (ip[0]) == 172 and (ip[1]) i...
def _sort_imports(x): """Sort a list of tuples and strings, for use with sorted.""" if isinstance(x, tuple): if x[1] == '__main__': return 0 return x[1] return x
def is_rel(s): """ Check whether a set represents a relation (of any arity). :param s: a set containing tuples of str elements :type s: set :rtype: bool """ # we have the empty relation, i.e. set() if len(s) == 0: return True # all the elements are tuples of the same len...
def first_true(iterable, pred=None, default=None): """Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true.""" # first_true([a,b,c], default=x) --> a or b or c or x # first_true...
def cyclic_mod(value: int, min_inclusive: int, max_inclusive: int) -> int: """ Given a value x and a range [a, b], wraps x so that it lies within the range [a, b] """ return ((value - min_inclusive) % (max_inclusive - min_inclusive + 1)) + min_inclusive
def select_dict(subset, superset): """ Selects a subset of entries from the superset :return: the subset as a dict """ res = {} for key in subset: if key in superset: res[key] = superset[key] return res
def fiber_packages(packages): """ Retrieve all packages of type 'Fibra' :param: list of packages """ lista = [] for pacote in packages: if pacote['tipo'] == 'Pacotes Fibra': lista.append(pacote) return lista
def first_word(text: str) -> str: """ returns the first word in a given text. """ li_text = text.split() doc = list(li_text) return doc[0] # another pattern return text[0:2]
def match_hostmask(prefix, mask): """ Match a prefix against a hostmask. :param bytes prefix: prefix to match the mask against :param bytes mask: a mask that may contain wildcards like ``*`` or ``?`` :return: ``True`` if the prefix matches the mask, ``False`` otherwise """ prefix_index = m...
def calculate_iou(gt, pr, form='pascal_voc') -> float: """Calculates the Intersection over Union. Args: gt: (np.ndarray[Union[int, float]]) coordinates of the ground-truth box pr: (np.ndarray[Union[int, float]]) coordinates of the prdected box form: (str) gt/pred coordinates format ...
def isUnspecified(str): """ Checks whether a string is None or an empty string. Returns a boolean. """ return str == "" or str is None
def try_key(dictionary, key, default): """ Try to get the value at dict[key] :param dictionary: A Python dict :param key: A key :param default: The value to return if the key doesn't exist :return: Either dictionary[key] or default if it doesn't exist. """ try: return dictionary[...
def _args_formatting(args, extra_args, indices): """utility function to be used in the Tensor class to correctly join the args and extra_args based on the indices Parameters: ----------- args: List extra_args: List indices: List of binary values the indices (one per element) to j...
def parse_field(field, field_name): """Parse field according to field type. Parameters ---------- field: str, dict field to be parsed. When a dictionary is given, it will return it as is. When a string is provided it will return the eval version of it, in order to return a dict ...
def flatten_dict(d, prefix="", separator="."): """ Flatten netsted dictionaries into a single level by joining key names with a separator. :param d: The dictionary to be flattened :param prefix: Initial prefix (if any) :param separator: The character to use when concatenating key names """ ...
def changeword(word): """ SH -> S2 """ newword = word.replace('SH','S2') return newword
def kml_header(name="",description=""): """ generate kml header """ kmlheader = """<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="https://www.opengis.net/kml/2.2"> <Folder> <name>%s</name> <description><![CDATA[<strong>%s</strong>]]></description> """ return kmlheader % (name, descriptio...
def correct_gps_week_crossovers(time_diff: float) -> float: """ Repairs over and underflow of GPS time, that is, the time difference must account for beginning or end of week crossovers. The time difference (time_diff) is the difference between a given GNSS epoch time t and toc: time_diff = t -...
def valid_symbol(symbol): """Returns whether the given symbol is valid according to our rules.""" if not symbol: return 0 for s in symbol: if not s.isalnum() and s != '_': return 0 return 1
def esf(speedup_pass, nthreads_pass): """Empirical Serial Fraction, given parallel speedup and number of threads (after [Tornatore, 2019])""" return ((1.0 / float(speedup_pass)) - (1.0 / float(nthreads_pass))) / ( 1.0 - (1.0 / float(nthreads_pass)) )
def modified_cauchy_cooling_sequence(initial_t, tf, l, t): """ Calculates the new temperature per iteration using a modified cauchy progression. Parameters ---------- initial_t : float initial temperature tf: float final temperature l: int number of iterations t: float actual temperature Returns ----...
def pair_hexvalue(value, delimiter=":"): """ Pair hex values (string) using delimiter. e.g. abcdef -> ab:cd:ef :param value: :param delimiter: :return: """ return delimiter.join( ["{}{}".format(a, b) for a, b in zip(value[::2], value[1::2])] )
def parse_client_cert_pair(config_value): """Parses the client cert pair from config item. :param config_value: the string value of config item. :returns: tuple or none. """ if not config_value: return client_cert = config_value.split(':') if len(client_cert) != 2: tips = ('...
def line_between(_x, _y, _a, _b): """Bresenham's line algorithm that returns a list of points.""" _points_in_line = [] _dx = abs(_a - _x) _dy = abs(_b - _y) _nx, _ny = _x, _y _sx = -1 if _x > _a else 1 _sy = -1 if _y > _b else 1 ...
def get_local_file_name(url: str) -> str: """ Get package source local file name from it's url :param url: source of the file :return: filename """ return url.split("/")[-1]
def iterative_fibonacci(i): """Iterative solution""" seq = [0, 1] if i in seq: return i, seq[i - 1], seq[:i] while i > len(seq): seq.append(seq[-1] + seq[-2]) return i, seq[-1], seq
def cast_pars_dict(pars_dict): """Cast the bool and float elements of a parameters dict to the appropriate python types. """ o = {} for pname, pdict in pars_dict.items(): o[pname] = {} for k, v in pdict.items(): if k == 'free': o[pname][k] = bool(int(...
def _normalize_custom_param_name(name): """Replace curved quotes with straight quotes in a custom parameter name. These should be the only keys with problematic (non-ascii) characters, since they can be user-generated. """ replacements = (("\u2018", "'"), ("\u2019", "'"), ("\u201C", '"'), ("\u201D"...
def split_traceback(tb, remove_class_name = False): """ Splits the given traceback into (stacktrace, message). """ startidx = -1 while True: startidx = tb.find('\n', startidx+1) if startidx < 0: break # No stacktrace if not tb.startswith(' ', startidx+1): ...
def check_not_finished_board(board: list) -> bool: """ Check if skyscraper board is not finished, i.e., '?' present on the game board. Return True if finished, False otherwise. >>> check_not_finished_board(['***21**', '4?????*',\ '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***']) False ...
def get_attr_from_dot_notation(obj, notation): """get_attr_from_dot_notation( {'a': {'c': 1, 'd': 2}, 'b': 3}, 'a.c.1' ) == {'a': {'c': 1}}""" r = notation.split('.', 1) att_name = r[0] other_notations = r[1] if len(r) > 1 else None if obj and att_name in obj: att_value = obj[at...
def count_simulation_problem_batches(n_simulation_problem_chunks, n_simulation_problems, n_simulation_problem_batches_per_chunk): """ Count batches to be generated. :param n_simulation_problem_chunks: number of chunks of simulation problems :param n_simulation_probl...
def in_between_points_on_list(points_list, divisions): """ This takes a list of numerical values (floats or ints) and a list of divisions of ints of (points_list) - 1. This method will then uses the number of sub divisions within the list of divisions to add new points to the points list where you have ...
def indent(level): """ Indent the text to a specified level :param level: The number of 4 space increments :return: String containing the desired number of spaces for indentation """ return level * ' '
def is_string(obj): """ Check if an object is a string """ return isinstance(obj, str)
def check_n8_safe(x: int, y: int, width: int, height: int): """ Checks if bound checking is needed """ if 0 < x - 1 and x + 1 < width: if 0 < y - 1 and y + 1 < height: return True return False
def parse_pull_spec(spec): """Parse <registry>[:port]/<repository>[@<digest>|:tag]""" server_port, repository_ref = spec.split('/', 1) if '@' in repository_ref: repository, ref = repository_ref.rsplit('@', 1) else: repository, ref = repository_ref.rsplit(':', 1) return 'https://' +...
def powerset(s): """ Generate the powerset of a """ new_s = [[]] for elt in s: new_s += [x + [elt] for x in new_s] return new_s
def flatten_aggregated_list_results(paged_results, item_key): """Flatten a split-up list as returned by GCE "aggregatedList" API. The compute API's aggregatedList methods return a structure in the form: { items: { $group_value_1: { $item_key: [$items] }, ...
def _describe_images_response(response): """ Generates a response for a describe images request. @param response: Response from Cloudstack. @return: Response. """ return { 'template_name_or_list': 'images.xml', 'response_type': 'DescribeImagesResponse', 'response': respo...
def check_type(value): """ Check the value means number or string. :param value: str :return: type """ try: int(value) except ValueError: try: float(value) except ValueError: type='string' return type
def reverse(x): """ :type x: int :rtype: int """ if x < 0: x = str(x)[:0:-1] x = int("-" + x) else: x = str(x)[::-1] x = int(x) if x > 2**31 - 1 or x < -2**31: return 0 return x
def unset_bit(string: int, pos: int) -> int: """Return bitstring with the bit at the position unset Args: string (int) - bit string pos (int) - position in the bit string """ return string & ~(2**pos)
def sort_fragments_by_elf10wbo(frags): """ Sort fragments by ELF10 WBO. This helps with plotting all distributions so the distributions of the different clusters are together Parameters ---------- frags : dict {'smiles': {'ensamble': , 'individual_confs': []} Returns ------- ...
def has_multiple_words(text): # accepts input from users """ check if user entered multiple words and convert them into 1 hypenated words""" words = (text.lower()).split() key_word = "" if len(words) > 1: key_word += "-".join(text.split()) else: key_word += text return key_word
def get_diffs(routes1, routes2, route_ids): """Get difference in number of routes using each segment. params - routes1: Dict{str : List[(lon, lat)]} - first set of routes - routes2: Dict{str : List[(lon, lat)]} - second set of routes - route_ids: List[str] - IDs of routes to consider return...
def _node_name_listener(target, value, oldvalue, initiator): """Listen for Node.name being modified and update path""" if value != oldvalue: target._update_path(newname=value) return value
def validate_params(params, required_params, validate_values=False): """ Make sure the iterable params contains all elements of required_params If validate_values is True, make sure params[k] are set. If required_params is a dictionary, make sure params[k] are set to the values given >>> validate_params(['a','b'...
def on_challenge(js): """ Responds with the 'challenge' parameter. https://api.slack.com/events/url_verification """ return { "challenge": js["challenge"] }, 200
def resolve(name, user_config, flags, default=None): """Resolve the provided option from either user_config or flags. If neither is set, use the default. If both are set, the flags take precedence. """ answer = user_config.get(name, default) if getattr(flags, name, None): answer = getat...
def scan_for_armature(objs, look_for_mhx=False): """ scans the objects for armatures """ for o in objs: if o.type != 'ARMATURE': continue if 'MhxRig' in o: if o['MhxRig'] == 'MHX' and look_for_mhx: return o else: if 'root' i...
def chromosome(data): """ Get the chromosome, if known. This treats 'UN' as unknown meaning unknown. """ chrom = data["chromosome"] if chrom == "UN": return None return chrom
def factorial(n): """This function returns factorial of positive integar n.""" """where n = 0 will return 1 as 0! = 1. Where n < 0 returns Invalid argument warning""" if n == 0: return 1 elif n < 0: return print('INVALID ARGUMENT, Positive integars only please!!') else: ...
def longest_repetition(chars): """ >>> assert(longest_repetition(None) == ('', 0)) >>> assert(longest_repetition('') == ('', 0)) >>> assert(longest_repetition('a') == ('a', 1)) >>> assert(longest_repetition('ab') == ('a', 1)) >>> assert(longest_repetition('aaaaaabbbbbcccc') == ('a', 6)) >>> ...
def load_data(batch_size,*args,**kwargs): """ Load data and build dataloader. Parameters ---------- batch_size : int batch size for batch training. Returns ------- trainloader : Dataloader Dataloader for training. testloader : Dataloader Dataloader for test. ...
def lookup(name, namespace): """ Get a method or class from any imported module from its name. Usage: lookup(functionName, globals()) """ dots = name.count('.') if dots > 0: moduleName, objName = '.'.join(name.split('.')[:-1]), name.split('.')[-1] module = __import__(moduleName) ...
def map_locale_to_rfc5646___alpha(the_locale: str): """RFC 5646""" d = {'zh-cn': 'zh-Hans', 'zh-hk': 'zh-Hant', 'zh-tw': 'zh-Hant'} the_locale = the_locale.replace('_', '-').lower() return d.get(the_locale, the_locale.split('-')[0])
def contains_pua(expected_values): """Is any of the code points in the Private Use Area?""" for charstring in expected_values: c = ord(eval("u'" + charstring + "'")) if 0xf800 <= c <= 0xf8ff: return True return False
def get_cursor(database_connection, cursor_parameters): """Execute the passed SQL query with search string string if one exists and returns the resulting cursor object.""" try: cursor = database_connection.cursor() if len(cursor_parameters) == 2: cursor.execute(cursor_parameters[0], ...
def get_schedule_weekdays(schedule): """ returns a list of weekdays the specified schedule is active """ return [schedule["weekday"]] if schedule.get("weekday", None) is not None else range(1, 8)
def join_plus(xs, check_non_empty=False): """ Concatenate strings with '+' to form legend label. Parameters ---------- xs : list List of strings check_non_empty : bool If True, assert that len(xs) > 0 Returns ------- str Concatenation of xs (e.g., "CPU + GPU") ...
def chunklistWithOverlap(inlist, size_per_chunk, overlap_per_chunk): """Convert list into a list of lists such that each element is a list containing a sequential chunk of the original list of length size_per_chunk""" assert size_per_chunk >= 1 and overlap_per_chunk >= 0 and size_per_chunk > overlap_per...
def dotadd (vec1, vec2): """Adds `vec1` and `vec2` element-wise.""" return [ e1 + e2 for e1, e2 in zip(vec1, vec2) ]
def _idx_filter_sort(query_op_tup): """ For performance, the order of filtering matters. It's best to do equality first before comparsion. Not-equal should be last becase a lot of values are liable to be returned. In and nin vary in how much they matter so go with not-equal :param query_op_tup ...
def get_ext(type): """Returns file extension Args: type (str): FILE_EXT from API response Returns: [str]: file extension string """ if type == "MP3": return "mp3" else: return "flac"
def uvalues(a, encoding='utf-8', fallback='iso-8859-1'): """Return a list of decoded values from an iterator. If any of the values fail to decode, re-decode all values using the fallback. """ try: return encoding, [s.decode(encoding) for s in a] except UnicodeError: return fal...
def parse_user(db_result): """ Takes a single user row DB result and puts it into a parsable form """ result = { "uid": db_result[0], "username": db_result[1], "password": db_result[2] } return result
def convert_camelcase_to_description(name: str) -> str: """Convert camel-case name to descriptive text. :param name: The camel-case name. :return: The descriptive text. """ cursor = 0 words = [] while cursor < len(name): find_position = cursor + 1 while find_position < len(...
def is_valid_account_name(name): """ Non-exhaustive check on account name validity. Will not false-fail a valid name, but might false-pass an invalid name if it doesn't follow some of the nitty-gritty rules. This is tolerable. Full rule set here: https://github.com/bitshares/bitshares-core/bl...
def is_power_of_two(n: int) -> bool: """Return True if the given number *n* is a power of two. :param int n: number to check :return: True if *n* is a power of two, False otherwise. :rtype: bool """ return (n != 0) and ((n & (n - 1)) == 0)
def substitute(template, subs):# {{{ """Defines a set of substitutions for a template""" for sec, subdict in subs.items(): if sec == 'required': for key, value in subdict.items(): template = value.join(template.split(f'%%{key}%%')) else: if subdict['includ...
def _normpath(path): """Normalize a path. Normalizes a path by removing unnecessary path-up segments and its corresponding directories. Providing own implementation because import os is not allowed in build defs. For example ../../dir/to/deeply/nested/path/../../../other/path will become...
def get_jurisdiction_flag(data: dict) -> str: """ Returns location_id from a data dictionary, or defaults to None :param dict data: The event data :return str|None: A string containing the location id, or None """ try: within_juris = data["event"]["data"]["new"]["austin_full_purpose"] ==...
def hhmmss(sec_in): """ Convert elapsed time in seconds to "d days hh:mm:ss.ss" format. This is nice for things that take a long time. """ h = int(sec_in // 3600) m = int(sec_in % 3600 // 60) s = sec_in % 3600 % 60 if h < 24: hstr = "{0:0>2}".format(h) elif h >= 24 and h < 48...
def nav_active(context, item): """ Returns 'active' is item is the active nav bar item, and '' otherwise. """ default = '' try: url_name = context['request'].resolver_match.url_name except: return default if url_name == item: return 'active' return default
def model_snowdepth(Snowmelt = 0.0, Sdepth_t1 = 0.0, Snowaccu = 0.0, E = 0.0, rho = 100.0): """ - Name: SnowDepth -Version: 1.0, -Time step: 1 - Description: * Title: snow cover depth Calculation * Author: STICS * Refer...
def rk4(f, x0, y0, x1, n, *args): """Runge-Kutta for pure pythonic solutions. """ vx = [0] * (n + 1) vy = [0] * (n + 1) h = (x1 - x0) / float(n) vx[0] = x = x0 vy[0] = y = y0 for i in range(1, n + 1): k1 = h * f(x, y, *args) k2 = h * f(x + 0.5 * h, y + 0.5 * k1, *args) ...
def get_entity_repr(serialization_context, serializer_cls, entity): """ Retrieves the dictionary representation of an entity. :param serialization_context: The context used for serialization. This is useful because it contains the request context, which in turns contain the user who made the request...
def dotproduct(vec1, vec2): """Compute the dot product of two vectors. :param vec1: the first vector :param vec2: the second vector """ # dotproduct([1, 2, 3], [1, 2, 3]) -> 14 return sum(map(lambda x, y: x * y, vec1, vec2))
def get_list_from_lines(lines): """"Convert a string containing a series of lines into a list of strings """ return [line.rstrip() for line in lines.splitlines()]
def Knl(n, l): """ return Hernquist K_{nl} Hernqusit & Ostriker 1992 eq. 2.23 Garavito-Camargo et al. eq. A5 """ return 0.5*n*(n+4*l+3) + (l+1)*(2*l+1);