content
stringlengths
42
6.51k
def reduce(args): """ >>> reduce([(2, 4), (4, 9)]) [(2, 4), (4, 9)] >>> reduce([(2, 6), (4, 10)]) [(2, 10)] """ if len(args) < 2: return args args.sort() ret = [args[0]] for next_i, (s, e) in enumerate(args, start=1): if next_i == len(args): ret[-1] = ret[-1]...
def isKanji(char): """ return true if char is a kanji or false if not """ code = ord(char) return 0x4E00 <= code <= 0x9FFF
def find_artifact(event): """ Returns the S3 Object that holds the artifact """ try: object_key = event['CodePipeline.job']['data']['inputArtifacts'][0] \ ['location']['s3Location']['objectKey'] bucket = event['CodePipeline.job']['data']['inputArtifacts'][0] \ ['l...
def make_relative(path: str, root_path: str) -> str: """Make path relative with respect to a root directory Arguments: path (str): current path. root_path (str): root directory path. Returns: str: relative path. """ r_path = path.replace(root_path, '') if r_path: ...
def is_valid_hcl(hcl: str) -> bool: """ (Hair Color) - a # followed by exactly six characters 0-9 or a-f. :return: Status of field (true = valid). :rtype: bool """ if hcl[0] != "#": return False if len(hcl[1:]) != 6: return False return True
def argsort(t, reverse=False): """Given a list, sort the list and return the original indices of the sorted list.""" return sorted(range(len(t)), key=t.__getitem__, reverse=reverse)
def get_parent_resource(project): """Returns the parent resource.""" return f'projects/{project}'
def bytes_to_int15(b0, b1): """Convert two bytes to 15-bit signed integer.""" value = (b0 | (b1 << 8)) >> 1 if value > 16383: value -= 32768 return value
def _makeDefValues(keys): """Returns a dictionary containing None for all keys.""" return dict(((k, None) for k in keys))
def Floor(x, factor=10): """Rounds down to the nearest multiple of factor. When factor=10, all numbers from 10 to 19 get floored to 10. """ return int(x/factor) * factor
def bubble_sort(array: list) -> tuple: """"will return the sorted array, and number of swaps""" total_swaps = 0 for i in range(len(array)): swaps = 0 for j in range(len(array) - 1): if array[j] > array[j + 1]: array[j], array[j + 1] = array[j + 1], array[j] ...
def get_wind_direction(degrees): """ Return the shorthand direction based on the given degrees. :type degrees: str, float :param degrees: integer for degrees of wind :type: str :return: wind direction in shorthand form """ try: degrees = int(degrees) except ValueError: ...
def redshift_num2str(z: float): """ Converts the redshift of the snapshot from numerical to text, in a format compatible with the file names. E.g. float z = 2.16 ---> str z = 'z002p160'. """ z = round(z, 3) integer_z, decimal_z = str(z).split('.') integer_z = int(integer_z) decimal_z = int(decimal_z) return f...
def diagonal_win(board, who): """ returns true if either diagonal contains a winner """ if board[0] == who and board[4] == who and board[8] == who: return True if board[2] == who and board[4] == who and board[6] == who: return True return False
def decode_digital_bitstream(waveform): """Extracts a bitstream from the waveform at the specified position""" result = [] for i, bit in enumerate(waveform): try: next_bit = waveform[i + 1] # No more words, so we are finished except IndexError: break ...
def is_name_selector(selector): """ A basic method to determine if a selector is a name selector. """ if selector.startswith("name=") or selector.startswith("&"): return True return False
def remove_none(l: list) -> list: """ Returns a list that does not contain any`None` values. @param l: The list to filter @return: a new list """ return list(filter(None, l))
def escape(x): """Escape brackets, '['' and ']'.""" return x.replace("[", "\\[").replace("]", "\\]")
def odd(x): """``odd :: Integral a => a -> Bool`` Returns True if the integral value is odd, and False otherwise. """ return x % 2 == 1
def rgb(arg): """Convert a comma separate string of 3 integers to RGB values""" colors = arg.split(',') if len(colors) == 1: try: r = int(colors[0]) except ValueError: raise ValueError('Colour should be a single integer or ' + \ '3 comma s...
def reference_vector_argument(arg): """ Determines a reference argument, so as not to duplicate arrays of reals, vectors and row vectors, which usually have the same implementation. :param arg: argument :return: reference argument """ if arg in ("array[] real", "row_vector"): return ...
def orderedSet(iterable): """ Remove all duplicates from the input iterable """ res = [] for el in iterable: if el not in res: res.append(el) return res
def speed_convert_bit(ukuran: float) -> str: """ Hi human, you can't read bit? """ if not ukuran: return "" totals_isi = {0: '', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'} totals = 2**10 no = 0 while ukuran > totals: ukuran /= totals no += 1 return "{:.2f} {}B".forma...
def is_list_of_strings(value): """ Check if all elements in a list are strings :param value: :return: """ return bool(value) and isinstance(value, list) and all(isinstance(elem, str) for elem in value)
def _fast_copy_probs_table(table): """ Copy a dictionary representation of a probability table faster than the standard deepcopy. :param dict table: A dictionary with the tuples of ints as keys and floats as values. :return: The copied table. """ table_copy = {tuple(assign): value for assign, v...
def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if number < 0: return -1 if number == 0: return 0 if number == 1: retu...
def abbrv_num(num): """Shorten string representation of large numbers by single-letter notation and rounding to 2 decimals Arguments: num (int): (Large) number to be formatted Return: Abbreviated and rounded number with single-letter notation """ magnitude = 0 while...
def has_doc(f): """Check if function has doc string.""" return f.__doc__ is not None
def get_prim_obj_from_sol(sol, parameters=None): """ Gets the primal objective from the solution of the LP problem Parameters ------------- sol Solution of the ILP problem by the given algorithm parameters Possible parameters of the algorithm Returns ------------- p...
def read_np_archive(archive): """Load Numpy archive file into a dictionary, skipping any values that cannot be loaded. Args: archive: Loaded Numpy archive. Returns: Dictionary with keys and values corresponding to that of the Numpy archive, skipping any values that could not ...
def get_next_breakpoint(distanceToGround, breakpoints): """Returns the next breakpoint based on the current distance from the ground. Keyword arguments: quantity -- How many colors inside the array (default: 1) """ for breakpoint in breakpoints.values(): if distanceToGround < breakpoint...
def has_type(actual_value, expected_type): """Return whether actual_value has expected_type""" return type(actual_value) is expected_type
def list_to_str(lst, space=False): """ convers list as a comma seperated string""" if space: base_str = ', ' else: base_str = ',' return base_str.join((str(c) for c in lst)).rstrip()
def normalize_org(org): """Internal function to normalize an org reference to a URN.""" if org.startswith('psc:org:'): return org return f"psc:org:{org}"
def nth_line(src, lineno): """ Compute the starting index of the n-th line (where n is 1-indexed) >>> nth_line("aaa\\nbb\\nc", 2) 4 """ assert lineno >= 1 pos = 0 for _ in range(lineno - 1): pos = src.find('\n', pos) + 1 return pos
def is_target_platform(ctx, platform): """ Determine if the platform is a target platform or a configure/platform generator platform :param ctx: Context :param platform: Platform to check :return: True if it is a target platform, False if not """ return platform and pla...
def tie(p, ptied = None): """Tie one parameter to another.""" if (ptied == None): return p for i in range(len(ptied)): if ptied[i] == '': continue cmd = 'p[' + str(i) + '] = ' + ptied[i] exec(cmd) return p
def a2_comp(number, nb_bits): """Compute the A2 complement of the given number according to the given number of bits used for encoding. >>> a2_comp(5, 8) 251 >>> a2_comp(-5, 8) 5 >>> a2_comp(-5, 9) 5 :param int number: the number to compute the A2 complement from. :param int nb_bit...
def get_standard_metadata_value( md_map, file, metadata ): """ Gets metadata values from a file path :param md_map: Dictionary of keys to callables to extract metadata. Callables should accept a single parameter which is the file name. :param file: The file path to search :param metadat...
def bool_from_env(env_value): """Convert environment variable to boolean.""" if isinstance(env_value, str): env_value = env_value.lower() in ['true', '1'] return env_value
def palindrome(word): """Return True if the given word is a palindrome.""" return word == word[::-1]
def dict_enter(dct, key, default): """Access dictionary entry with a default value""" if key not in dct: dct[key] = default return dct[key]
def identifier_appearance_stat_key(appearances: set) -> str: """Return the key given the appearances of the span.""" if {'templates', 'references'} <= appearances: return 'in_tag_ref_and_template' elif 'templates' in appearances: return 'only_in_template' elif 'references' in appearances...
def explore_local(starting_nodes, large_component, other_nodes, look_for, upper_bound): """ Search the large component graph for additional nodes (evidence) that doesnt conflict with other nodes or the upper bound on copy number. If a conflict is found, no nodes of that type are returned :param starting...
def Any(cls): # noqa """ Use during testing to assert call value type. The function will return an instantiated class that is equal to any version of `cls`, for example using string. >>> mock = MagicMock() >>> mock.func("str") >>> mock.func.assert_called_once_with(Any(str)) ...
def historical_site_validation(historical_sites): """ Decide if the historical site input is valid. Parameters: (str): A user's input to the historical site factor. Return: (str): A single valid string, such as "1", "0" or "-5" and so on. """ while historical_sites ...
def partition_targets(targets): """partition all targets""" included_targets, excluded_targets = [], [] for target in targets: if target.startswith("-"): excluded_targets.append(target[1:]) else: included_targets.append(target) return included_targets, excluded_t...
def separate_types(data): """Separate out the points from the linestrings.""" if data['type'] != 'FeatureCollection': raise TypeError('expected a FeatureCollection, not ' + data['type']) points = [] linestrings = [] for thing in data['features']: if thing['type'] != 'Feature': ...
def to_host_list(value): """Space separated list of FQDNs.""" return value.split()
def color_triple(color): """Convert a command line colour value to a RGB triple of integers.""" # FIXME: Somewhere we need support for greyscale backgrounds etc. if color.startswith('#') and len(color) == 4: return (int(color[1], 16), int(color[2], 16), int(color[3], ...
def _get_expression_levels(expr): """ :returns: dictionary with the level of depth of each part of the expression. Brackets are ignored in the result. e.g.: ['A', 'OR', 'B', 'AND', '(', 'A', 'IF', '(', 'NOT', 'C', 'IF', 'D', ')', ')'] => {0: [0, 1, 2, 3], 1: [5, 6], 2: [8, 9, 10, 11]} """ level ...
def parse_float(word): """ Parse into float, on failure return 0.0 """ try: return float(word) except ValueError: return 0.0
def format_string( oldString ): """ This function turns a given string (one of the two arguments passed to the script by the user) into one that can be used as part of the URL used to fetch the page from the lyrics wiki. Specifically, it needs to be camel- case (or 'title' case) with underscores re...
def if_entry_table(if_name): """ :param if_name: given interface to cast. :return: PORT_TABLE key. """ return b'PORT_TABLE:' + if_name
def build_variant_display_title(chrom, pos, ref, alt, sep='>'): """ Builds the variant display title. """ return 'chr%s:%s%s%s%s' % ( chrom, pos, ref, sep, alt )
def get_rst_bold(text): """ Return text bold """ return f"**{text}** "
def get_crc16(data, offset, length): """ Computes CRC16 :param data: ByteArray wich contains the data :param offset: Data offset to begin the calculation :param length: Number of bytes after the offset :return: Integer (4 bytes) with CRC or 0000 on error """ if data is None or offset < 0...
def _get_list_difference(group_1, group_2): """ Calculates the difference between the two event value group. The returned lists are always a copy of the original. Parameters ---------- group_1 : `None`, `list` of `Any` The first group. group_2 : `None`, `list` of `Any` ...
def objc_strip_extension_registry(lines): """Removes extensionRegistry methods from the classes.""" skip = False result = [] for line in lines: if '+ (GPBExtensionRegistry*)extensionRegistry {' in line: skip = True if not skip: result.append(line) elif line == '}\n': skip = False ...
def filter_by_tags(queries, tags): """ Returns all the queries which contain all the tags provided """ return [q for q in queries if all(elem in q['tags'] for elem in tags)]
def indent(lines, spaces=4): """ Indent the given string of lines with "spaces" " " and strip trailing newline. """ indented = [" "*spaces+line.strip() for line in lines.split("\n")] return ("\n".join(indented)).rstrip()
def parse_orig_dest_get(params, keys = ['origin', 'destination']): """ Normalize origin and destination keys in the GET request. """ for key in keys: if len(params[key]) == 5: # Port code == 5-character uppercase string params[key] = str(params[key]).upper() else: ...
def height_correction(height1, height2): """returns height correction in m""" return (height1 - height2) * 0.0065
def n_interactions(nplayers, repetitions): """ The number of interactions between n players Parameters ---------- nplayers : integer The number of players in the tournament. repetitions : integer The number of repetitions in the tournament. Returns ------- integer ...
def check_diagonal_winner(board) -> bool: """checks for diagonal winner""" mid = board[1][1] if mid is not None: if board[0][0] == mid == board[2][2]: return True if board[2][0] == mid == board[0][2]: return True return False
def damping_maintain_sign(x, step, damping=1.0, factor=0.5): """Damping function which will maintain the sign of the variable being manipulated. If the step puts it at the other sign, the distance between `x` and `step` will be shortened by the multiple of `factor`; i.e. if factor is `x`, the new value ...
def ImagePropFromGlobalDict(glob_dict, mount_point): """Build an image property dictionary from the global dictionary. Args: glob_dict: the global dictionary from the build system. mount_point: such as "system", "data" etc. """ d = {} if "build.prop" in glob_dict: bp = glob_dict["build.prop"] ...
def l1(vector_1, vector_2): """ compute L2 metric """ return sum([abs((vector_1[i] - vector_2[i])) for i in range(len(vector_1))])
def join_ipv4_segments(segments): """ Helper method to join ip numeric segment pieces back into a full ip address. :param segments: IPv4 segments to join. :type segments: ``list`` or ``tuple`` :return: IPv4 address. :rtype: ``str`` """ return ".".join([str(s) for s in segments])
def get_xdot(y, p_x): """speed in x direction, from coordinates and momenta""" v_x = p_x + y return v_x
def matmul(Ma, Mb): """ @brief Implements matrix multiplication. """ assert len(Ma[0]) == len(Mb), \ "Ma and Mb sizes aren't compatible" size = len(Mb) Mres = [[0 for i in range(size)] for j in range(size)] for i in range(size): for j in range(size): fo...
def clean_string(string): """Removes non-letters from string leaving only ascii letters (swedish characters removed), whitespace and hyphens. Returns the clean string. """ new_string = "" string.lower() for c in string: if c.isalpha() or c.isspace() or c == '-': new_string +=...
def int_to_based_string(number: int, states: str, length: int = 0) -> str: """Generates the quivalent string representation of an integer in the provided base states Parameters: ----------- number: int integer value to be represented state...
def getStrips(seq): """ find contained intervals where sequence is ordered, and return intervals in as lists, increasing and decreasing. Single elements are considered decreasing. "Contained" excludes the first and last interval. """ deltas = [seq[i+1] - seq[i] for i in range(len(seq)-1)] increasing...
def strip_type(caller): """ strip the -indel or -snp from the end of a caller name """ vartype = '' if caller.endswith('-snp'): caller = caller[:-len('-snp')] vartype = 'snp' elif caller.endswith('-indel'): caller = caller[:-len('-indel')] vartype = 'indel' ...
def verify_image_name(in_dict): """Verifies post request was made with correct format The input dictionary must have the appropriate data keys and types, or be convertible to correct types, to be added to the image database. Args: in_dict (dict): input with image name Returns: st...
def convert_mw(mw, to="g"): """(int_or_float, str) => float Converts molecular weights (in dalton) to g, mg, ug, ng, pg. Example: >> diploid_human_genome_mw = 6_469.66e6 * 660 #lenght * average weight of nucleotide >> convert_mw(diploid_human_genome_mw, to="ng") 0.0070904...
def to_py_name(cpp_name, entry_type): """Returns the name the function should have in the Python api, based on the c++-function name. For entry_type 'function', the cpp_name is used unmodified, otherwise strip everything before the first underscore, so that e.g: > someclass_some_method...
def load_step_solve(n1,n2,inc=1): """ Solve from load step n1 to n2 """ _lss = "LSSOLVE,%g,%g,%g"%(n1,n2,inc) return _lss
def _get_changed_items(baselist, comparelist): """Return changed items as they relate to baselist.""" return list(set(baselist) & set(set(baselist) ^ set(comparelist)))
def pow(base, exp, mod): # pylint: disable=redefined-builtin """ Efficiently exponentiates an integer :math:`a^k (\\textrm{mod}\\ m)`. The algorithm is more efficient than exponentiating first and then reducing modulo :math:`m`. This is the integer equivalent of :func:`galois.poly_pow`. Note ...
def filtered_objects(objects, typeid_filter_list=None, include_only_visible=False): """Filter list of objects.""" if typeid_filter_list is None: typeid_filter_list = [ "App::Line", "App::Plane", "App::Origin", # 'GeoFeature', # 'PartDesign::Coo...
def format_duration(sec): """ Format duration in seconds Args: sec (int): seconds since 1970... """ hours,remainder = divmod(sec,3600) min = remainder//60 ftime = "%s:%s" % (str(hours).rjust(2,'0'),str(min).rjust(2,'0')) return str(ftime).rjust(5)
def add_cocs(original, additional): """Add two tuples of COCs. Extend as needed.""" assert not (original is None and additional is None), "No COCs to add!" if original is None: return additional elif additional is None: return original else: common = tuple(lhs + rhs for lhs,...
def reverse_gray_code(g): """Restores number n from the gray code!""" n = 0 while g: n ^= g g >>= 1 return n
def unit_format(x_in): """ Define helper unit format function for axis :param x_in: a number in decimal or float format :return: the number rounded and in certain cases abbreviated in the thousands, millions, or billions """ # suffixes = ["", "Thousand", "Million", "Billion", "Trillion", "Quadr...
def list_values(keys, dictionary): """Returns `dictionary` values orderd by `keys`. >>> d = {'1': 1, '2': 2} >>> list_values(['1', '2', '3'], d) [1, 2, None] """ return [key in dictionary and dictionary[key] or None for key in keys]
def classify(tree, input): """ tree is our decision model and input is unknown every time it recurse it choose a subtree """ # if this is a leaf node, return its value if tree in [True, False]: return tree attribute, subtree_dict = tree # see the attribute of input one by one subtre...
def starting_regions(num_state_qubits): """ For use in bisection search for state preparation subroutine. Fill out the necessary region labels for num_state_qubits. """ sub_regions = [] sub_regions.append(['1']) for d in range(1,num_state_qubits): region = [] for i in range(2...
def snake_to_spaces(snake_cased_str): """ convert snake case into spaces seperated """ separator = "_" components = snake_cased_str.split(separator) if components[0] == "": components = components[1:] if components[-1] == "": components = components[:-1] if len(components...
def check_for_essid(essid, lst): """Will check if there is an ESSID in the list and then send False to end the loop.""" check_status = True # If no ESSIDs in list add the row if len(lst) == 0: return check_status # This will only run if there are wireless access points in the list. for...
def _valueish(val): """ Try to convert something Timetric sent back to a Python value. """ literals = {"null":None, "true":True, "false":False} v = val.lower() return v in literals and literals[v] or float(v)
def get_colours(query, clusters): """Colour array for Plotly.js""" colours = [] for clus in clusters: if str(clus) == str(query): colours.append('rgb(255,128,128)') else: colours.append('blue') return colours
def leap_year(year: int): """ The tricky thing here is that a leap year occurs: on every year that is evenly divisible by 4 except every year that is evenly divisible by 100 except every year that is evenly divisible by 400 :param year: :return: """ if year %...
def join_by_comma(iterable, key=None): """ Helper to create a comma separated label out of an iterable. :param iterable: an iterable to be joined by comma :param key: if the iterable contains dicts, which key would you want to extract :return: comma separated string """ if key: thing...
def file_as(name: str) -> str: """Returns a human's name with the surname first, or tries to at least. This may perform poorly with some names. `file_as('Mary Wollstonecraft Shelley')` returns `'Shelley, Mary Wollstonecraft'`""" parts = name.split() if not parts or len(parts) == 1: return...
def round_off(value, digits=2): """ Rounding off the value :param float value: Value to be rounded :param digits: Digit to kept as after point :return float: Rounded value """ return float(("{0:.%sf}" % digits).format(value))
def _dup(x): # pylint: disable=invalid-name """Helper: copy the top element of a list or a tuple.""" if isinstance(x, list): return [x[0]] + x assert isinstance(x, tuple) return tuple([x[0]] + list(x))
def ArchForAsmFilename(filename): """Returns the architectures that a given asm file should be compiled for based on substrings in the filename.""" if 'x86_64' in filename or 'avx2' in filename: return ['x86_64'] elif ('x86' in filename and 'x86_64' not in filename) or '586' in filename: return ['x86']...
def rotate_axes(xs, ys, zs, zdir): """ Reorder coordinates so that the axes are rotated with zdir along the original z axis. Prepending the axis with a '-' does the inverse transform, so zdir can be x, -x, y, -y, z or -z """ if zdir == 'x': return ys, zs, xs elif zdir == '-x': ...