content
stringlengths
42
6.51k
def multiple(a, b): """Return the smallest number n that is a multiple of both a and b. >>> multiple(3, 4) 12 >>> multiple(14, 21) 42 """ "*** YOUR CODE HERE ***" r1 = a % b if (r1 == 0): GCD = b else: r2 = b % r1 while (r2 != 0): r1, r2 = r2,...
def polygonArea(xy_vals): """Calculate the area of an irregular polygon. Args: xy_vals(list): containing a tuple in each element with the x and y values for the geometry data. Return: double - the area of the polygon. """ n = len(xy_vals) area = 0.0 for i in ra...
def safe_numpy_to_native(num): """Safely convert a numpy object to a native Python object. :param num: the numpy object to convert. :returns: the native Python object corresponding to the numpy object. """ try: return num.item() except: return num
def overlap_probability(ngram, table, smoothing=0.0, stopwords=None): """Returns the probability that the given n-gram overlaps with the table. A simple implementation which checks how many tokens in the n-gram are also among the values in the table. For tables with (attribute, value) pairs on the `value` fiel...
def format_or(items): """Return a string of comma separated items, with the last to items separated by "or". [1, 2, 3] -> "1, 2 or 3" """ formatted_items = [] for item in items: try: item = "'" + item + "'" except TypeError: item = str(item) f...
def is_int(s): """return True or False if input string is integer or not.""" try: int(s) return True except ValueError: return False
def bufsize_type_to_bufsize(bf_type): """ for a given bufsize type, return the actual bufsize we will read. notice that although 1 means "newline-buffered", we're reading a chunk size of 1024. this is because we have to read something. we let a StreamBufferer instance handle splitting our chunk on new...
def reads_by_prefix(config): """Return read meta by prefix""" reads = {} if "reads" not in config: return {} for strategy in ("paired", "single"): if not strategy in config["reads"] or not config["reads"][strategy]: continue for entry in config["reads"][strategy]: ...
def __santize_args(args: dict) -> dict: """ Attempt to sanitize input arguments for things like improper types and Null values. Lists are converted to comma separated lists and None type values are converted to '' :param args: dictionary of variables from the skillet with values from the user, default ...
def singleGridIndexToGridIndex(i, nx, ny, nz): """ Convert a single into a grid index (3 indices): :param i: (int) single grid index :param nx, ny, nz: (int) number of grid cells in each direction :return: ix, iy, iz: (3-tuple) grid index in x-, y-, z-axis direct...
def get_predicted_gender(spanish_sent): """ Return the gender of the first entity in the spanish translation. """ first_word = spanish_sent.split()[0].lower() if first_word == "el": return "male" elif first_word == "la": return "female" else: return "neutral"
def Sign(num): """ Returns the sign of ``num`` (either -1 or 1, or 0 if ``num`` is 0). Parameters ---------- num : float Input number """ if num == 0: return 0 if num > 0: return 1 return -1
def compress_register_array(registers): """ Take and array and compress it by removing duplicates. Looks for duplicated names such as foo0, foo1, foo2 etc, and then checks the fields match. """ # Return an array of [register name, register, None or count] ret = [] current_reg = None c...
def calc_unmapped_score(alignments, obs_max, end): """ Returns the unmapped score :param alignments: list, alignments for a given read :param obs_max: int, obs_max alignment score :param end: str, single of paired :return: score """ if end == "single": alignments = sorted(alignme...
def clean_json(resource_json, resources_map): """ Cleanup the a resource dict. For now, this just means replacing any Ref node with the corresponding physical_resource_id. Eventually, this is where we would add things like function parsing (fn::) """ if isinstance(resource_json, dict): ...
def binary_to_int(binary: str) -> int: """Convert a binary string to an integer Args: binary (str): Binary string Returns: int: Integer value of binary string """ return int(binary, 2)
def find_test_index(test, selected_tests, find_last_index=False): """Find the index of the first or last occurrence of a given test/test module in the list of seleceted tests. This function is used to determine the indexes when slicing the list of selected tests when ``options.first``(:attr:`find_last_inde...
def deepmerge(a, b): """ Merge dict structures and return the result. >>> a = {'first': {'all_rows': {'pass': 'dog', 'number': '1'}}} >>> b = {'first': {'all_rows': {'fail': 'cat', 'number': '5'}}} >>> import pprint; pprint.pprint(deepmerge(a, b)) {'first': {'all_rows': {'fail': 'cat', 'number'...
def request_cert(session, domain_name, validation_domain): """Requests a certificate in the AWS Certificate Manager for the domain name Args: session (Session|None) : Boto3 session used to communicate with AWS CertManager If session is None no action is performed ...
def ant_2_containing_baslines(ant, antennas): """ Given antenna returns list of all baselines among given list with that antenna. """ baselines = list() for antenna in antennas: if antenna < ant: baselines.append(256 * antenna + ant) elif antenna > ant: b...
def gformat(value): """ Format value for directory name. :param value: value :type value: float :return: str :rtype: str """ return ('%.7f' % float(value)).rstrip('0').replace('.', '')
def sum_numbers(*args: float) -> float: """ calculates the sum of all the numbers passed as arguments """ result = 0 for arg in args: result += arg return result
def _format_skill_order(skill_order): """ Formats recommended skill order into shorthand notation. Output example: "Q.E.W.Q, Q>E>W" means lv1: Q, lv2: E, lv3: W, lv4: Q, then max Q first, then E, then W. """ skills = { "q": 0, "w": 0, "e": 0, } shorthand = [] ...
def get_foreign_key_checks(enabled): """ Gets the query the enable / disable FOREIGN_KEY_CHECKS. :type bool :param enabled: Whether or not to enable :rtype str :return A query """ return 'SET FOREIGN_KEY_CHECKS={0:d}'.format(enabled)
def simple_mapper(stream): """ Returns a simple list of tuples: [(<key1>, 1), (<key2>, 1)...] based on data in stream """ return list(map(lambda key: (key, 1), stream))
def combine(*dicts): """Given multiple dicts, merge them into a new dict as a shallow copy.""" super_dict = {key: val for d in dicts for key, val in d.items()} return super_dict
def porosity_total(phie, vclay, phiclay): """ Converts effective porosity to total porosity Parameters ---------- phie : float Effective porosity (decimal) vclay : float Volume of clay (decimal) phiclay : float Clay porosity - taken from a shale interval (decimal) ...
def absorption_coefficient(t, r): """The absorption coefficient :param t: the transmission coefficient :param r: the reflection coefficient :return: The absorption coefficient """ return 1 - (t + r)
def flat_cell(cell): """ flat dictionarys in celss """ if isinstance(cell, dict): value_cell = list(cell.values())[0] else: value_cell = cell return value_cell
def chunkify(lines, limit=2000): """ Creates chunks of strings from the given lines. Parameters ---------- lines : `list` of `str` Lines of text to be chunkified. limit : `int`, Optional The maximal length of a generated chunk. Returns ------- result : `list...
def calc_map_dims(x_size, y_size, mp_size, mp_dpi): """ Calculate output map size. :param x_size: <int or float> Image x dimension :param y_size: <int or float> Image y dimension :param mp_size: <int> Percent of image space of which the map will occupy :param mp_dpi: <int> Map density, as dots ...
def is_chinese_char(cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean...
def eval_having(pred, gold): """ Args: Returns: """ pred_total = gold_total = cnt = 0 if len(pred['groupBy']) > 0: pred_total = 1 if len(gold['groupBy']) > 0: gold_total = 1 pred_cols = [unit[1] for unit in pred['groupBy']] gold_cols = [unit[1] for unit in gold['gro...
def convert_value(val): """ Convert string to the most appropriate type, one of: bool, str, int, None or float :param str val: the string to convert :return bool | str | int | float | None: converted string to the most appropriate type """ if not isinstance(val, str): try: v...
def first_matching_item(iterable, predicate): """ Gets the first item in an iterable that matches a predicate (or None if nothing matches) Returns: Matching item or None """ return next(filter(predicate, iterable), None)
def container_from_filename(bids_or_caps_filename): """Extract container from BIDS or CAPS file. Args: bids_or_caps_filename (str): full path to BIDS or CAPS filename. Returns: Container path of the form "subjects/<participant_id>/<session_id>" Examples: >>> from clinica.utils.nipyp...
def _time_string(minutes): """Time D-hh:mm:ss format.""" minutes = max(minutes, 0) seconds = int(round((minutes % 1) * 60)) hours, minutes = divmod(int(minutes), 60) return f'{hours:02}:{minutes:02}:{seconds:02}'
def get_valid_region(location): """Make sure that region is not `Location.DEFAULT` (empty string)""" if not location: return 'us-east-1' else: return location
def apply(input): """ This h2o algorithm loads the h2o.init() operation, and then proceeds with normal hello world """ return "hello " + input
def _str_to_bool(value: str) -> bool: """ Parse string into bool. It tries to match some predefined values. If none is matches, python bool(value) is used. :param value: string to be parsed into bool :return: bool value of a given string """ if isinstance(value, str): if value.lowe...
def manhattan_distance(port): """Calculates the Manhattan distance from a node to the central port Args: port ((int,int)): coordinates of the port Returns: int: the Manhattan distince from the port to the central port """ return abs(port[0]) + abs(port[1])
def generate_vals(param_specs): """Generate values from specs. :param param_specs: dictionary where the value is in regex format :return: dictionary with generated values for regexs """ if isinstance(param_specs, dict): current_info = \ dict((k, generate_vals(v)) for k, v in pa...
def vowel_count(phrase): """Return frequency map of vowels, case-insensitive. >>> vowel_count('rithm school') {'i': 1, 'o': 2} >>> vowel_count('HOW ARE YOU? i am great!') {'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1} """ vowels = "AEIOUaeiou" return_map = {} for...
def shorten_key(key): """ Convert a dot-map string like "foo.bar.baz" into "f.b.baz" """ *heads, tail = key.split(".") new_key_builder = [] for subkey in heads: if len(subkey) > 0: new_key_builder.append(subkey[0]) new_key_builder.append(tail) return ".".join(new_key_...
def class_has_parent(_class: type, parent_class: type) -> bool: """Checks if a class has a given parent class""" for base in _class.__bases__: if base == parent_class: return True return False
def key_with_minval(d): """Get the key with minimum value in a dictionary Paramerers: d (dictionary) """ try: v=list(d.values()) k=list(d.keys()) return k[v.index(min(v))] except: return 9999
def serialize_txindex(txindex: int) -> bytes: """Serializes txindex to bytes""" return txindex.to_bytes(4, byteorder="little")
def get_machine_run_flowcell_id(runid_and_flowcellid): """return machine-id, run-id and flowcell-id from full string. Expected string format is machine-runid_flowcellid >>> get_machine_run_flowcell_id("HS002-SR-R00224_BC9A6MACXX") ('HS002', 'HS002-SR-R00224', 'BC9A6MACXX') >>> get_machine_run_flowc...
def wrap_with_half_check(test_string): """Wraps test_string with a check for cl_khr_fp16 if appropriate""" string = 'if (testDevice.has_extension("cl_khr_fp16")) {\n' string += test_string string += '}\n' return string
def csv_addition(buf): """ Convert a csv string into ints and then add them. """ chars = buf.split(",") result = 0 for c in chars: result += int(c) return result
def recovery_secret_to_ksk(recovery_secret): """Turn secret and salt to the URI. >>> recovery_secret_to_ksk("0123.4567!ABCD") 'KSK@babcom-recovery-0123.4567!ABCD' """ if isinstance(recovery_secret, bytes): recovery_secret = recovery_secret.decode("utf-8") # fix possible misspellings...
def create_zero_list(number_of_segments): """ Create a list of zeros for the Iris AO :param number_of_segments: int, the number of segments in your pupil :return: list of tuples with three zeros, the length of the number of total segments in the DM """ return [(0., 0., 0.)] * number_of_segments
def sluggify(text): """ Create a file system friendly string from passed text by stripping special characters. Use this function to make file names from arbitrary text, like titles :param text: :return: """ if not text: return '' data = ''.join([c for c in text if c.isalpha() or...
def default_symbol_resolve(symbol_mapping): """Resolve any conflict in a symbol mapping. The argument `symbol_mapping` maps candidate new symbol names (e.g., the names of Python attributes in the namespace returned by :func:`importr`) to a sequence of original symbol names (e.g., the names of objec...
def get_leaves(nodes): """Return a list containing the leaves of the graph defined by nodes.""" leaves = [] for n in nodes: if not n.children: leaves.append(n) return leaves
def order_by_weight(value): """ Orders a list of categories based on their weights. :param value: :return: """ return sorted((category for category in value), key=lambda x: x.weight)
def stringify_rank(rank : int) -> str: """Converts the rank into a str. eg Rank 1 --> 1st""" if rank is None: return ">100th" output = str(rank) if output[-2:] in ("11", "12", "13"): output += "th" elif output[-1] == '1': output += "st" elif output[-1] == '2'...
def is_valid_deck(deck_of_cards): """ (list of int) -> bool A valid deck contains every integer from 1 up to the number of cards in the deck. Return True if and only if the deck_of_cards is a valid deck of cards. >>> is_valid_deck([1, 4, 3, 2]) True >>> is_valid_deck([]) Fal...
def _unescape_xml(xml): """ Replace escaped xml symbols with real ones. """ return xml.replace('&lt;', '<').replace('&gt;', '>').replace('&quot;', '"')
def find_value_after_0(steps, target): """Find value after 0 when target is inserted, with number steps each.""" position = 0 cur_value = 0 for number in range(1, target + 1): position = (position + steps + 1) % number if position == 0: cur_value = number return cur_value
def dedup_and_title_case_names(names): """Should return a list of title cased names, each name appears only once""" return [x.title() for x in sorted(list(set(names)))]
def makelower(indict): """return a copy of a string->string dict such that all keys and values are lowercase.""" return {k.lower(): v for k, v in indict.items()}
def pad_sequences(sequences, pad_tok=None, max_length=None): """ Pad sequence. Args: sequences: A sequence needs to be padded. pad_tok: Token used for padding. max_length: Maximal length of the sequence Returns: The sequence after padding and the length of the padded sequence. ...
def clean_lines(input_list): """ Clean the final output lines """ output_list = [] for line in input_list: output_list.append(' '.join(line.split()[:5])) return output_list
def fix_subnets(data1): """ :param data1: :return: """ data=str(data1) data=data.replace("'", "") data=data.replace("[", "") data=data.replace("]", "") return data
def grid_sum(grid): """ To make code more readable. :param grid: A 2x2 grid to return the sum of. :return: The sum of a 2x2 grid. """ return grid[0][0] + grid[0][1] + grid[1][0] + grid[1][1]
def is_number(obj): """Is a python object a number?""" try: complex(obj) # for int, long, float and complex except ValueError: return False return True
def bytes_to_long(bytesdata: bytes) -> int: """ Converts an 8-byte sequence to a long integer. Args: bytesdata: 8 consecutive bytes, as a ``bytes`` object, in little-endian format (least significant byte [LSB] first) Returns: integer """ assert len(bytesdata) == 8 ...
def extract_auto_refresh_profiles(profiles): """Pull out any profiles with the prefix 'auto-refresh-' in the name. Parameters ---------- - profiles - the profiles read from the aws credentials file Returns ------- A dict of profiles that are prefixed by 'auto-refresh-' in the name. """...
def find_duplicates_0(_list): """ deprecated. Find duplicate items in a list :arg list _list: a python list """ return set([x for x in _list if _list.count(x) > 1])
def decode_enums(obj, available_enums=None): """ Decode enums from parsed yaml file :param obj: object to check :param available_enums list of available enums classes to decode :return: decoded object """ if isinstance(obj, dict): new_obj = {} for...
def _ToShortStr(arg): """Gets a short string representation of an object.""" if hasattr(arg, '__name__'): return arg.__name__ return str(arg)
def tohex(byte_array): """Convert a byte array to a HEX string representation.""" return "".join("%02x " % b for b in byte_array)
def square_of_sum(limit): """ Returns the square of the sum of all integers in the range 1 up to and including limit. """ return sum([i for i in range(limit + 1)]) ** 2
def scatter(iterable, n): """ Evenly scatters an interable by `n` blocks. Sourced from: http://stackoverflow.com/questions/2130016/splitting-a-list-of-arbitrary-size-into-only-roughly-n-equal-parts :param iterable: An iterable or preferably a 1D list or array. :param n: An inte...
def transMatrix(x, y, z): """Generate translation matrix x,y,z -- scale vector """ T = [ [1.,0.,0.,0.], [0.,1.,0.,0.], [0.,0.,1.,0.], [x,y,z,1] ] return T
def stack_pointer(c): """stack pointer""" v = "c.sp" return v
def scale_and_shift_func(x, params, has_scale: bool, has_shift: bool): """Example of a scale and shift function.""" if has_scale and has_shift: scale, shift = params return x * scale + shift elif has_scale: return x * params[0] elif has_shift: return x + params[0] else: raise ValueError()
def inclusion_one_default(one, two='hi'): """Expected inclusion_one_default __doc__""" return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)}
def psf_shape_tag_from_psf_shape_2d(psf_shape_2d): """Generate an image psf shape tag, to customize phase names based on size of the image PSF that the original PSF \ is trimmed to for faster run times. This changes the phase name 'phase_name' as follows: image_psf_shape = 1 -> phase_name image_ps...
def unique(in_list, key=None): """Unique values in list ordered by first occurance""" uniq = [] if key is not None: keys = [] for item in in_list: item_key = key(item) if item_key not in keys: uniq.append(item) keys.append(item_key) ...
def is_hex_str_w_0x(s): """String formatted as a hexadecimal number with 0x prefix.""" try: int(s, 16) return type(s) is str and s[0:2] == '0x' except: return False
def get_script_name(pidx): """Return where this script resides, so we can load it!""" if pidx >= 200: name = 'scripts200/p%s' % (pidx, ) elif pidx >= 100: name = 'scripts100/p%s' % (pidx, ) else: name = 'scripts/p%s' % (pidx,) return name
def index_sort_key(x): """Sorting key to use for getar frame indices""" return (len(x), x)
def triangle_shape(height): """ draws the the triangle of x Args: height ([int]): [the height of the triangle] Returns: [string]:[the triangle of x] """ if height == 0: return "" else: r = [ (height - i - 1) * " " + (2 * i + 1) * "x" + (height - i -...
def powerResidue(N, seed=None, a=273673163155, c=13, M=2**48): """ Calculate a series of random numbers """ import datetime if seed == None: print("Seed value set to NONE, defaulting to system time.") seed=int(datetime.datetime.now().strftime("%Y%m%d%H%M%s")) else: pass ...
def str_trunc_begin(S, L): """Returns a possibly truncated S (ellipsis added at the string's beginning) if the length of S is greater than L. L should be equal to or greater than 3 to be making sense.""" if len(S) > L: return "..." + S[min(-L+3,0):] else: return S
def _sorted_steps(steps, sort_step_key): """Return a sorted list of steps. :param sort_step_key: If set, this is a method (key) used to sort the steps from highest priority to lowest priority. For steps having the same priority, they are sorted from highest interface priority to lowest. :re...
def get_run_time(start_time, end_time): """Calculate and return the run time (string and seconds float). start_time and end_time are both floats of seconds since the epoch. Args: start_time (float): When the run started end_time (float): When the run ended Returns: str: How lo...
def keys_exists(element, *keys): """ Check if *keys (nested) exists in `element` (dict). """ if not isinstance(element, dict): raise AttributeError('keys_exists() expects dict as first argument.') if len(keys) == 0: raise AttributeError('keys_exists() expects at least two arguments, ...
def most_common(l): """ Helper function. :l: List of strings. :returns: most common string. """ # another way to get max of list? #from collections import Counter #data = Counter(your_list_in_here) #data.most_common() # Returns all unique items and their counts #data.most_...
def get_2d_pos(position, shape=[[0, 27], [0, 27]]): """ Convert a 1D representation to 2D. @param position: The 1D position (sequence). @param shape: The shape of the region. """ y_len = shape[1][1] - shape[1][0] + 1 x = position % y_len y = (position - x) / y_len return [x, y]
def find_matches_scripts(name, scripts): """ This function ... :param name: :param scripts: :return: """ # Get a list of the script names that match the first command line argument, if there is one if "/" in name: matches = [] dir_name = name.split("/")[0] scri...
def normalize_title(title): """Normalize titles. """ return title.strip().title()
def mixColor( originalColor, overColor): """ Use overColor's alpha to overlay it on top of original Color Color parameters in form [r, g, b, a] Returns [r, g, b, 1] """ alpha = overColor[3] if alpha == 1: return overColor[:4] else: out = [0, 0, 0, 1] for i in range(3): out[i] = originalColor[i] * (1 - ...
def flatten(l): """Flatten a nested list.""" return sum(map(flatten, l), []) \ if isinstance(l, list) or isinstance(l, tuple) else [l]
def getv(dict, key, d=None): """Lookup key in dict and return value or the supplied default.""" if key in dict: return dict[key] return d
def inv_log_spectrogram(log_spec): """Inverse the log representation of the spectrogram or mel spectrogram.""" return 10 ** (log_spec / 10)
def dsl_escape(stringa, all=False): """Helper for escaping the full-text inner query strings, when they includes quotes. EG with the query string: '"2019-nCoV" OR "COVID-19" OR "SARS-CoV-2" OR (("coronavirus" OR "corona virus") AND (Wuhan OR China))' In Python, if you want to embed it int...
def add_none_params(params, list_added): """ Some time we get error when get the non exist keys, so add it using this code :param params: params :param list_added: list keys you want to add :return: """ for p in list_added: try: params[p] except KeyError: ...