content
stringlengths
42
6.51k
def reflect(point0, point1): """Reflects off-curve control point in relation to on-curve one. Used for smooth curves.""" px = point1[0] + (point1[0] - point0[0]) py = point1[1] + (point1[1] - point0[1]) return (px, py)
def get_reorientations(in_orient, out_orient): """Generates a list of axes flips and swaps to convert from in_orient to out_orient Args: in_orient (str): 3-letter input orientation out_orient (str): 3-letter output orientation Raises: Exception: Exception raised if in_orient or ou...
def format_sys_time(seconds): """ Convert total seconds to fromatted HH:MM:SS string """ s = seconds % 60 m = (seconds // 60) % 60 h = (seconds // 3600) % 3600 return "{:02d}:{:02d}:{:02d}".format(h, m, s)
def iio_uri(_iio_emu_func): """URI fixture which provides a string of the target uri of the found board filtered by iio_hardware marker. If no hardware matching the required hardware is found, the test is skipped. If no iio_hardware marker is applied, first context uri is returned. If list of hardware ...
def tobytes(value): """Convert value to bytes.""" if isinstance(value, bytes): return value else: if isinstance(value, str): return value.encode() else: return bytes(value)
def comp_binary_same(term, number): """ :param term: :param number: :return: """ for i in range(len(term)): if term[i] != '-': if term[i] != number[i]: return False return True
def compile_str_from_parsed(parsed): """The (quasi-)inverse of string.Formatter.parse. Args: parsed: iterator of (literal_text, field_name, format_spec, conversion) tuples, as yield by string.Formatter.parse Returns: A format string that would produce such a parsed input. >>> ...
def splitQuery(text): """Function that process message and returns query and database""" maintext = text.replace('\xa0', ' ').split(" ", 1)[1].split("\n", 1) query = maintext[1].replace("```", "").replace("\n", " ").strip() db = maintext[0].strip() return query, db
def divide(x, y): """ Question 5.6: Given two positive integers, compute their quotient, using only the addition, subtraction, and shifting operators """ result = 0 power = 32 y_power = y << power while x >= y: while y_power > x: y_power >>= 1 power -...
def F2C(F): """Convert Fahrenheit to Celcius""" return (F - 32) / 1.8
def stringfromtime(t, accuracy=4): """ :param t : Time in seconds :returns : Formatted string """ m, s = divmod(t, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) components = [] if d > 0: components.append(f"{int(d)} day" + ("s" if d > 1 else "")) if h > 0: compon...
def hexStrToInt(inputstr): """ Converts a string with hex bytes to a numeric value Arguments: inputstr - A string representing the bytes to convert. Example : 41414141 Return: the numeric value """ valtoreturn = 0 try: valtoreturn = int(inputstr,16) except: valtoreturn = 0 return valtoreturn
def _fix_mimic_icd(icd): """ Add the decimal to the correct location for the ICD code From the mimic documentation (https://mimic.physionet.org/mimictables/diagnoses_icd/): > The code field for the ICD-9-CM Principal and Other Diagnosis Codes > is six characters in length, with the dec...
def contains_term_from_list(name, terms): """ Iter check for term :param name: :param terms: :return: """ for term in terms: if name.__contains__(term): return True return False
def cc(col, ccol): """Color correction for pygame visualization. """ if ccol: return (col[0]/2, col[1], col[2]) else: return (col[2], col[1], col[0])
def split_apt(field): """ Parses the ADDRESS field (<site address>, <apt number> <municipality>) from the CLEMIS CFS Report and returns the apartment number. """ if ',' in field: f = field.split(', ') f = f[1] f = f.split(' ') apt = f[0] else: apt = None ...
def number_keys(a_dictionary): """Return the number of keys in a dictionary.""" return (len(a_dictionary))
def byteify(element): """Converts unicode elements of dict or list into str. # Source: # http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python """ if isinstance(element, dict): return {byteify(key): byteify(value) for ...
def header_dict_from_list(array): """Given a list of strings in http header format, return a dict. If array is None, return None""" if array is None: return array header_dict = {} for item in array: (key, sep, value) = item.partition(':') if sep and value: header_...
def fortran_float(string: str) -> float: """Construct :class:`float` from Fortran style float strings. This function can convert strings to floats in all of the formats below: * ``3.14e10`` (also parsable with :class:`float`) * ``3.14E10`` (also parsable with :class:`float`) * ``3.14...
def gates_to_coords(gates): """ This is a helper function for test_utils(). Given a set of gates, it extracts the coordinates of the qubits that the gates were applied to """ # Get gates and extract the coordinates, this is a bit tricky coords = [] [coords.append(g[1]) for g in gates if g[1]...
def my_reduce_function(results): """sums up the number of words by totaling the number of appearances of each word. @param results: dictionary that counts the appearances of each word within a url.""" final_result = 0 for count in results: for word in count: final_result += count[wor...
def transformation_normalizer(name: str) -> str: """Normalize the name of a transformation.""" return name.lower().replace('_', '').replace('transformation', '')
def _recipe_name(raw_configuration): """ Given a raw repository configuration, returns its recipe name. :param raw_configuration: configuration as returned by the SCRIPT_NAME_GET groovy script. :type raw_configuration: dict :return: name of the recipe ("format") """ name = raw_confi...
def fancy_format(in_str, **kwargs): """ A format command for strings that already have lots of curly brackets (ha!) :param in_str: :param kwargs: the arguments to substitute :return: >>> fancy_format('{haha} {dan} {bob}', dan = 1, bob = 2) '{haha} 1 2' """ new_str = in_str.replace('{...
def factorial(number: int) -> int: """ Calculating factorial of a number using prime decomposition method """ prime: list = [True] * (number + 1) result: int = 1 for i in range (2, number + 1): if prime[i]: j: int = 2 * i while j <= number: p...
def sdnv_encode(value): """Returns the SDNV-encoded byte string representing value Args: value (int): Non-negative integer that should be encoded Returns: bytes: SDNV-encoded number Raises: ValueError: If value not an integer or negative """ if value < 0 or not isinstanc...
def est_palindrome3(s : str) -> bool: """ ... cf. ci-dessus ... """ i : int for i in range(0,len(s)//2): if s[i] != s[-i-1]: return False return True
def make_vector(inFN1, inFN2=None, jointFusion=False): """ This function... :param inFN1: :param inFN2: :param jointFusion: :return: """ # print("inFN1: {0}".format(inFN1)) # print("inFN2: {0}".format(inFN2)) if inFN2 == None: returnVector = [inFN1] else: ret...
def is_file_genpath(genpath): """ Determine whether the genpath is a file (e.g., '/stdout') or not (e.g., 'command') :param genpath: a generalized path :return: a boolean value indicating if the genpath is a file. """ return genpath.startswith('/')
def manhattan_distance(x, y): """ Calculates the manhattan distance :param x: x position :param y: y position :return: int """ return abs(x) + abs(y)
def win_text(total_tests, passing_tests=0): """ The text shown in the main window. """ return "%d/%d" % (passing_tests, total_tests)
def _ws_url(host, rpc_opts): """ Given a hostname and set of config options returned by _rpc_opts, return the standard URL websocket endpoint for a Sideboard remote service. """ return '{protocol}://{host}/wsrpc'.format(host=host, protocol='wss' if rpc_opts['ca'] else 'ws')
def required_padding(address, alignment): """ Return how many padding bytes are needed to align address """ rest = address % alignment if rest: # We need padding bytes: return alignment - rest return 0
def relEqual(x, y, tol=2 ** -26): """ Simple test for relative equality of floating point within tolerance Default tolerance is sqrt double epsilon i.e. about 7.5 significant figures """ if y == 0: return x == 0 return abs(float(x) / float(y) - 1.) < tol
def electrolyte_TDF_base_Landesfeind2019(c_e, T, coeffs): """ Thermodynamic factor (TDF) of LiPF6 in solvent_X as a function of ion concentration and temperature. The data comes from [1]. References ---------- .. [1] Landesfeind, J. and Gasteiger, H.A., 2019. Temperature and Concentration D...
def get_variables(models): """get variables of all models Args: models: dict containing all the models available Returns: variables: variables of all models """ variables = [] for model in models.keys(): variables += models[model].variables return variables
def named_capturing(pattern, name): """ generate a named capturing pattern :param pattern: an `re` pattern :type pattern: str :param name: a name for the capture :type name: str :rtype: str """ return r'(?P<{:s}>{:s})'.format(name, pattern)
def primes(n): """ Returns a list of primes < n """ sieve = [True] * n for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i]: sieve[i * i :: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1) return [2] + [i for i in range(3, n, 2) if sieve[i]]
def find_blank_position(grid, blank): """Returns the number of row, from bottom, that contains the blank value.""" for i, row in enumerate(grid[::-1]): if blank in row: return i + 1
def run_and_read_all(run_lambda, command): """Runs command using run_lambda; reads and returns entire output if rc is 0""" rc, out, _ = run_lambda(command) if rc is not 0: return None return out
def iscomplex(pscale): """ Returns whether pscale is an instance of a complex number """ return isinstance(pscale, complex)
def _Cond(test, if_true, if_false): """Substitute for 'if_true if test else if_false' in Python 2.4.""" if test: return if_true else: return if_false
def _get_1st_obj(ll): """given a list [of list ...] of something get the first non-list object """ if type(ll) is not list: return ll return _get_1st_obj(ll[0])
def query_finder(line): """Split record on rows that start with query label.""" return line.startswith("# Query:")
def get_dataset_by_code(activity_code, data): """get the dataset specified by an activity id from a database""" dataset = [i for i in data if i['code'] == activity_code][0] return dataset
def round_scores(student_scores): """ :param student_scores: list of student exam scores as float or int. :return: list of student scores *rounded* to nearest integer value. """ return [round(score) for score in student_scores]
def axisheader2dic(header): """ Convert axisheader list into dictionary """ dic = dict() dic["nucleus"] = str(header[0]).strip('\x00') dic["spectral_shift"] = header[1] dic["npoints"] = header[2] dic["size"] = header[3] dic["bsize"] = header[4] dic["spectrometer_f...
def frequency(text, char): """ Counts frequency of a character in a string. """ count = 0 for c in text: if c == char: count += 1 return count
def classes(*names, convert_underscores=True, **names_and_bools): """Join multiple class names with spaces between them. Example ------- >>> classes("foo", "bar", baz=False, boz=True, long_name=True) "foo bar boz long-name" Or, if you want to keep the underscores: >>> classes("foo", "bar...
def extended_gcd(a, b): """ Return r, s, t such that gcd(a, b) = r = a * s + b * t """ r0, r1 = a, b s0, s1, t0, t1 = 1, 0, 0, 1 if r0 > r1: r0, r1, s0, s1, t0, t1 = r1, r0, t0, t1, s0, s1 while r1 > 0: q, r = divmod(r0, r1) r0, r1, s0, s1, t0, t1 = r1, r, s1, s0 - q ...
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
def byte_list_to_u32le_list(data, pad=0x00): """! @brief Convert a list of bytes to a list of 32-bit integers (little endian) If the length of the data list is not a multiple of 4, then the pad value is used for the additional required bytes. """ res = [] for i in range(len(data) // 4): ...
def build_record_unique_id(doc): """Build record unique identifier.""" doc['unique_id'] = '{0}_{1}'.format(doc['pid_type'], doc['pid_value']) return doc
def get_venv_command(venv_path: str, cmd: str) -> str: """Return the command string used to execute `cmd` in virtual env located at `venv_path`.""" return f"source {venv_path}/bin/activate && {cmd}"
def argmax(seq, fn): """Return an element with highest fn(seq[i]) score; tie goes to first one. argmax(['one', 'to', 'three'], len) 'three' return 0: used, 1: replace, 2: both """ if len(seq) == 1: return seq[0] best = -1 best_score = float("-inf") for x in seq: x_sco...
def is_isogram4(string: str) -> bool: """ Another person's solution. So concise! """ return len(string) == len(set(string.lower()))
def get_cloudera_sample_cut(sample_lines_ratio=None): """Get cut int value for sample proportion.""" if sample_lines_ratio is None: sample_lines_ratio = 1.0 # Generate the value for sample selection. sampling_cut = int(2 ** 64 * sample_lines_ratio / 2.0) - 1 return sampling_cut
def first_int(*args, default=1): """Parse the first integer from an iterable of string arguments.""" for arg in args: try: return int(arg) except ValueError: continue return default
def warmup_linear(x, warmup=0.002): """ Specifies a triangular learning rate schedule where peak is reached at `warmup`*`t_total`-th (as provided to BertAdam) training step. After `t_total`-th training step, learning rate is zero. """ if x < warmup: return x / warmup return max((x - 1.0) / (...
def seperate_list(list, division_part): """ Dividing list into equal parts or partialy equal parts Parameters ---------- list - list division_part - number of part to divide list into Returuns -------- out - single list containing all the divided lists """ ...
def offbyK(s1,s2,k): """Input: two strings s1,s2, integer k Process: if both strings are of same length, the function checks if the number of dissimilar characters is less than or equal to k Output: returns True when conditions are met otherwise False is returned""" if len(s1)==len(s2): ...
def divceil(divident, divisor): """Integer division with rounding up""" quot, r = divmod(divident, divisor) return quot + int(bool(r))
def get_adopters_for_advertisement(adoption_center, list_of_adopters, n): """ :param adoption_center: A single AdoptionCenter instance :param list_of_adopters: A list of Adopter (or a subclass of Adopter) instances. :param n: The number of adopters, up to a maximum of n, who will be sent advertisements...
def csv_name(str_name): """Add extension for file. return: String: File name with the extension .csv """ return f'{str_name}.csv'
def _is_instance(type_to_check, element, condition="any", deep=False): """ ----- Brief ----- Function that verifies when "all" or "any" elements of the list "element" have the type specified in "type_to_check" input. ----------- Description ----------- In some biosignalsnotebook...
def is_installed(module): """Tests to see if ``module`` is available on the sys.path >>> is_installed('sys') True >>> is_installed('hopefullythisisnotarealmodule') False """ try: __import__(module) return True except ImportError: return False
def parse_output(out, line=None): """ Function will parse given output and if some line starts with 'line', if will be removed Parameters ---------- out : bytes output from subprocess.check_output line : str prefix which will be removed """ lines = out.decode().strip().sp...
def site_read(context, data_dict): """\ This function should be deprecated. It is only here because we couldn't get hold of Friedrich to ask what it was for. ./ckan/controllers/api.py """ # FIXME we need to remove this for now we allow site read return {'success': True}
def assemble_clause_from_tokens(token_list): """ Assemble each string value from a list of tuples into a string, representing an individual clause in a cypher query :param token_list: A list of tuples in the format (Token, value) which is returned by the py2neo cypher lexer :return: string representing ...
def parameterized_config(template): """ https://github.com/apache/incubator-airflow/blob/master/airflow/configuration.py https://github.com/apache/incubator-airflow/blob/master/LICENSE Generates a configuration from the provided template + variables defined in current scope :param template: a c...
def _func_destroy_scheduler_session(sessionId, dask_scheduler): """ Remove session date from _raft_comm_state, associated with sessionId Parameters ---------- sessionId : session Id to be destroyed. dask_scheduler : dask_scheduler object (Note: this is supplied by DASK, not ...
def set_show_scroll_bottleneck_rects(show: bool) -> dict: """Requests that backend shows scroll bottleneck rects Parameters ---------- show: bool True for showing scroll bottleneck rects """ return {"method": "Overlay.setShowScrollBottleneckRects", "params": {"show": show}}
def find_target(LowerSeq, TargetLoc): """ Assigns TargetLoc Priorities for assigning target: 1. first coded (NE in LowerSeq that does not have the same code as SourceLoc; codes are not checked with either SourceLoc or the candidate target are compounds (NEC 2. first null-cod...
def _getSubtitleNumber(entry): """ Helper function that returns the subtitle number of a TTI block. Used to sort a list of TTI blocks by subtitle number. """ return entry['SN']
def connected_three(position: int, mask: int) -> bool: """ Return True, when the player has connected 3 and free space after/before them Arguments: position: bit representation of the board with players pieces mask: bit representation of board with all pieces Return: bool: True f...
def transpose(matrix): """ :returns the matrix transposed """ zipped_rows = zip(*matrix) transpose_matrix = [list(row) for row in zipped_rows] return transpose_matrix
def bs3_cols(num_entries): """Return the appropriate bootstrap framework column width. Args: num_entries (int): The number of entries to determine column width for. Returns: int: The integer value for column width. """ if not isinstance(num_entries, int): return 12 mapp...
def privacy_check(postal_code: str) -> bool: """ Helper function for the callbacks. Checks if postal code is private. --- Args: postal_code (str): Area postal code. Returns: True (bool): When postal code is in the private_list False (bool): When postal code is not foun...
def getClusters(taus, neighborsets): """ input: taus : values of overlap between two spin configurations. Array of N spin-values. neighborsets: list ordered by spin index, whose elements are the spins neighboring the spin at that index. output: list of cluster ...
def _get_cols_length(table, cols_num): """Return the max length of every columns. """ cols_length = [0] * cols_num for row in table: for (i, col) in enumerate(row): col_len = len(col) if col_len > cols_length[i]: cols_length[i] = col_len return cols_le...
def split_arg(arg: str) -> list: """ Splits arg string using comma separator and returns a filtered list :param arg: :return: """ args = arg.split(",") return [a.strip() for a in args if a]
def symmetric_difference_cardinality(s, q): """Return the cardinality of the symmetric difference of two sets. Parameters ---------- s : iterable Elements of the first set. Values must be hashable. q : iterable Elements of the second set. Values must be hashable. Returns --...
def clip(text, max_len=80): """Return max_len characters clipped at space if possible""" text = text.rstrip() if len(text) <= max_len or ' ' not in text: return text end = len(text) space_at = text.rfind(' ', 0, max_len + 1) if space_at >= 0: end = space_at else: spac...
def metric(x): """ This function will convert Metric meters to Imperial Feet (and Inches). :return: Converted value from Metric to Imperial """ # Initial conversion # Meters to Feet meters_in_ft = float("{:.4f}".format(x * 3.280839895)) # Inches portion of conversion meters_in_in ...
def street_check_fold_json( rus_check_json, benny_bet_json, rus_fold_json, oven_show_json ): """Expected JSON for street_check_fold model-fixture""" return { "actions": [ rus_check_json, benny_bet_json, rus_fold_json, oven_show_json, ...
def dirs(obj, st='', caseSensitive=False): """ I very often want to do a search on the results of dir(), so do that more cleanly here :param obj: the object to be dir'd :param st: the strig to search :param caseSensitive: If False, compares .lower() for all, else doesn't :return: The results...
def sanitise_keys(d): """ Strip all of the colons out of the key names :param d: :return: dict """ new_d = {} for k, v in d.items(): new_d[k.replace(':', '_')] = v return new_d
def regex_unanchor(regexp): """ ES regexps are anchored, so adding .* is necessary at the beginning and end to get a substring match. But we want to skip that if front/end anchors are explicitly used. Also avoid doubling up wildcards, in case the regexp engine is not smart about backtracking. ...
def empirical_hpd(values, conf=0.05): """ Assuming a **unimodal** distribution, returns the 0.95 highest posterior density (HPD) interval for a set of samples from a posterior distribution. Adapted from ``emp.hpd`` in the "TeachingDemos" R package (Copyright Greg Snow; licensed under the Artistic Li...
def lerp(p0, p1, t): """Linear interpolation.""" return (1.0 - t) * p0 + t * p1
def _number(s): """Given a numeric string, return an integer or a float, whichever the string indicates. _number("1") will return the integer 1, _number("1.0") will return the float 1.0. """ try: n = int(s) except ValueError: n = float(s) return n
def parseacclist(infile): """ parses the user specified accession list file parameters ---------- infile the name of the accession list input file returns ---------- acclist = a list containing each accession number from file """ acclist = [] try: with open(in...
def _calc_proprtn_srvd_unsrvd(total_pop, servd_pop, unsrvd_pop): """[summary] Args: total_pop (int): The total population for that category servd_pop (int): Of the population, those who are served ...
def test_row(counter): """ Tests if counter%4 is 0 :param counter: For loop counter :rtype: boolean """ if counter%4 == 0: return True return False
def _construct_GPL_url(accession): """Example URL: ftp://ftp.ncbi.nlm.nih.gov/geo/platforms/GPLnnn/GPL570/annot/GPL570.annot.gz """ number_digits = len(accession) - 3 # 'GPL' is of length 3. if number_digits < 4: folder = accession[:3] + 'nnn' # e.g. GPLnnn. elif 3 < number_digits < 5: folder = accession[...
def points_to_matrix(points): """List of points (x, y) is transformed into system of linear equations.""" degree = len(points) - 1 matrix = [[] for i in range(degree + 1)] vector = [] for i, point in enumerate(points): for j in range(degree, -1, -1): matrix[i].append(point[0] ** ...
def _round_fractions(fractions): """Format float fractions as rounded fraction strings. Fractions are rounded as short as possible without losing the precision necessary to distinguish one fraction from another. The rounding starts at 3 decimal places and continues up to 10 decimal places, if a shorter...
def string_is_equal_case_insensitive(subject: str, value: str) -> bool: """Case insensitive string is equal""" return subject.strip().lower() == value.strip().lower()
def reduce_vocab(word_vecs): """ just takes words already used, but reserves 0 """ uniques = set() for wv in word_vecs: uniques.update(wv) new2old = [0] # always map 0 to itself if 0 in uniques: uniques.remove(0) new2old.extend(sorted(uniques)) old2new = dict((w, i) f...