content
stringlengths
42
6.51k
def align_wrappers(command): """align all '\\\n' strings to be the largest offset from the previous '\n'""" # first, find the maximum offset posn = 0 max = -1 while 1: next = command.find('\n',posn) if next < 0: break if next > posn and command[next-1] == '\\': # ch...
def canonicalize(doc): """De-duplicate environment vars and sort them alphabetically.""" spec = doc.get('spec') if not spec: return doc template = spec.get('template') if not template: return doc spec2 = template.get('spec') if not spec2: return doc containers = spec2.get('containers') ...
def isint(s): """ Is the given string an integer?""" try: i = int(s) except ValueError: return False return True
def strepr(s): # type: (str) -> str """repr(s) without the leading "u" for Python 2 Unicode strings.""" return repr(s).lstrip("u")
def urljoin(*paths: str) -> str: """Join together a set of url components.""" # urllib's urljoin has a few gotchas and doesn't handle multiple paths return "/".join(map(lambda path: path.strip("/"), paths))
def extract_set(root: dict, nested_key_to_extract) -> set: """Extract value for given key from every dict in root.""" extract = set() for root_key in root: extract.add(root[root_key][nested_key_to_extract]) return extract
def _intersect(MatchingProts): """ intersections between matching proteins """ intersecs = [] for i,t1 in enumerate(MatchingProts): for j,t2 in enumerate(MatchingProts[i+1:]): # & is equal to .intersection() intersecs.append(t1&t2) if len(MatchingProts) == 3: ...
def check_plottype(ptype): """Verify the plottype""" assert isinstance(ptype, str), \ f'(TypeError) Plot type {ptype} must be a string' assert ptype in ['linear', 'log'], \ f'(ValueError) Plot option {ptype} not recognized' return None
def bytes_to_int32(b0, b1, b2, b3): """Convert two bytes to 16bit signed integer.""" value = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) if value > 2147483647: value -= 4294967296 return value
def isstream(instance): """ check if a instance is a stream """ try: import mmap i_am_not_mmap_obj = not isinstance(instance, mmap.mmap) except ImportError: # Python 2.6 or Google App Engine i_am_not_mmap_obj = True return hasattr(instance, "read") and i_am_not_mmap_obj
def _shape_for_channels(num_channels, *, length=None): """Returns the shape.""" return (length,) if num_channels == 1 else (length, num_channels)
def get_fortfloat(key, txt, be_case_sensitive=True): """ Matches a fortran compatible specification of a float behind a defined key in a string. :param key: The key to look for :param txt: The string where to search for the key :param be_case_sensitive: An optional boolean whether to search case-sen...
def __get_average_defective_rate__(qars: list, commune): """ Get the average of defective_rate in the commune passed as parameter in the benin republic area """ _all = list(filter(lambda c: c.commune == commune, qars)) total = 0 count = len(_all) if count == 0: count = 1 for i, ...
def to_float(value): """converts int to string""" if value=='rtl' or value=='right': return 'float:right!important;' if value=='ltr' or value=='left': return 'float:left!important;'
def create_input_list(pdb_list_fname): """ create a list of tuples (pdb_id, chain) from a text file """ pdb_list = [] with open(pdb_list_fname, 'r') as f: for record in f.read().splitlines(): pdb_id, chain = record[:-1], record[-1] # check PDB ID and chain are valid ...
def signed_int_str(input_int: int): """ Converts an integer into a string that includes the integer's sign, + or - :param int input_int: the input integer to convert to a signed integer string :return str signed_int_str: the signed integer string """ if input_int >= 0: return '+' + str(...
def point_respect_line(point, line): """ :param point: point of (x, y) :param line: line of two points (point1, point2), :return: an integer that >0, ==0, <0, if == 0 means point lies on the line """ # Method 1: cross product # (pnt1, pnt2) = line # v1 = [pnt2[0] - pnt1[0], pnt2[1] - p...
def remove_cnum(next_cell): """Function to remove the confluence number from the tuple containing the row/column number of the stream cell """ next_cellwocnum=[] for cell in next_cell: row=cell[0] col=cell[1] next_cellwocnum.append((row,col)) return next_cellwocnum
def empty(v, zero: bool = False, itr: bool = False) -> bool: """ Quickly check if a variable is empty or not. By default only '' and None are checked, use ``itr`` and ``zero`` to test for empty iterable's and zeroed variables. Returns ``True`` if a variable is ``None`` or ``''``, returns ``False`` if v...
def convert(data): """funcao que adciona A a C se data[A]==1""" c = [] for i in range(len(data)): if data[i] == 1: c.append(i) return c
def float_or_none(s): """Ensure a value is of type float if it is not none.""" if s: return float(s)
def escape_regex_chars(string): """Function to escape regex characters in a string""" string = string.replace('\\', '\\' + '\\').replace('^', '\^').replace('$', '\$').replace('.', '\.') string = string.replace('|', '\|').replace('?', '\?').replace('*', '\*').replace('+', '\+') string = string.replac...
def compute(x, y): """Compute sum of passed in arguments :param x: Integer (operand 1) :param y: Integer (operand 2) :rtype: Integer """ if x > 100 or x < 0 or y > 100 or y < 0: raise ValueError("Passed in value out of bounds") return x + y
def Intersection(x: list, y: list) -> list: """Elements that match between two lists.""" return list(set(x) & set(y))
def import_fullname(name, paths=None): """ Imports a variable or class based on a full name, optionally searching for it in the paths. """ paths = paths or [] if name is None: return None def do_import(name): if name and ('.' in name): module_name, name = name.rsplit...
def convert_to_type(input_value, new_type, input_value_name=None): """ Attempts to convert input_value to type new_type and throws error if it can't. If input_value is None, None is returned If new_type is None, input_value is returned unchanged :param input_value: Value to be converted :param ...
def is_semet(pdbin): """Check if a PDB format file is a selenomethione derivative""" with open(pdbin) as f: for line in f: if line[:6] == "ATOM " or line[:6] == "HETATM": if line[17:20] == "MET": return False if line[17:20] == "MSE": return True return False
def search_mergedcell_value(xl_sheet, merged_range): """ Search for a value in merged_range cells. """ for search_row_idx in range(merged_range[0], merged_range[1]): for search_col_idx in range(merged_range[2], merged_range[3]): if xl_sheet.cell(search_row_idx, search_col_idx).value:...
def repeat_inside(line): """ first the longest repeating substring """ print("************") cache = {} MAX_WINDOW = "" MAX_WINDOW_AMOUNT = 0 length = len(line) for i in range(len(line)-1, 0, -1): window_length = length // i for j in range(0, window_length): ...
def mock_get(pipeline, allowDiskUse): # pylint: disable=W0613,C0103 """ Return mocked mongodb docs. """ return [ {'_id': 'dummy_id_A', 'value': 'dummy_value_A'}, {'_id': 'dummy_id_B', 'value': 'dummy_value_B'}, ]
def intlist(val): """Turn a string of comma-separated ints into a list of ints. """ return [int(v) for v in val.split(',')]
def _is_tspair(filename): """ Checks whether a file is ASCII TSPAIR format. :type filename: str :param filename: Name of the ASCII TSPAIR file to be checked. :rtype: bool :return: ``True`` if ASCII TSPAIR file. .. rubric:: Example >>> _is_tspair('/path/to/tspair.ascii') # doctest: +S...
def offset_from_utc(meta): """Check whether the metadata set has time zone offset metadata, if exist, return its value, if not, return False. :param meta: Metadata dictionary :return: """ for key, val in meta.items(): if isinstance(val, dict): if 'offsetfromutc' in val: ...
def _dedupe_timestep(new_trck, cache, criteria, omits=None): """ Auxillary function for MuGen.edit.dedupe. Processes evnts in a timestep. """ n = len(cache) n_range = range(n) isdupe = [False] * n for i in n_range: if not isdupe[i]: if omits is None or not isinstance(...
def linear_rescale(min, max, value): """ Linearly rescale a value to 0 and 1 using the min and max values. :param min: :param max: :param value: :rtype: float """ x = (value - min)/(max - min) return x
def common_substring_from_start(str_a, str_b): """ returns the longest common substring from the beginning of str_a and str_b """ def _iter(): for a, b in zip(str_a, str_b): if a == b: yield a if a == ':' or b == ':': return el...
def tokenize_passage(text): """ Tokenizes a passage by paragraph :param text: passage :return: array of paragraphs """ output = [] for s in text.splitlines(): paragraph = s.strip() if len(paragraph) > 0: output.append(paragraph) return output
def convert_millies_to_time(millis): """ convert_millies_to_time: Function that converts milliseconds to time in Xh Ym format (i.e. 2h 15m). Used to include duration of tasks to the report. """ millis = int(millis) seconds = (millis / 1000) % 60 int(seconds) minutes = (millis / (1000 * 60)) % 6...
def WriteResponseFile(fnames): """WriteResponseFile(fnames) writes the file names to hdrstack """ f = open('hdrstack', 'w') for name in fnames: f.write(name +'\n') f.close() return True
def ip_stomac(ip): """ Convert ip from string to mac address. @parameter{ip,string} IP address with 4 dot-separated numbers (0-255). @returns{string} mac address """ return '02:00:%02x:%02x:%02x:%02x' % tuple([int(x) for x in ip.split('.')])
def getattribute(value, arg): """Gets an attribute of an object dynamically from a string name""" assert hasattr(value, str(arg)), "Invalid %s in %s" % (arg, value) return getattr(value, str(arg))
def test_warn(assertion, func='function', message='False assertion', verbose=True): """Tests if assertion can be interpreted as False. If this is the case, print a warning message, but continue the execution of the program. Returns True if problem found. This can be used in an if clause to perform additional ...
def resta(cu, cd): """(list, list) -> list Resta entre dos numeros complejos""" a = cu[0] - cd[0] b = cu[1] - cd[1] r= [a,b] return r
def is_url(url: str, allowed_url_prefixes=('http', 'ftp')) -> bool: """ Check url for prefix match. """ for prefix in set(allowed_url_prefixes): if url.startswith(prefix): return True return False
def retrieve_adjacency_list(cgpms, v_to_c): """Return map of cgpm index to list of indexes of its parent cgpms.""" return { i: list(set(v_to_c[p] for p in c.inputs if p in v_to_c)) for i, c in enumerate(cgpms) }
def format_vertex(vertex, id): """ Creates the written description of the vertex. Args: vertex: The vertex object. id: The id of the vertex. Returns: The string that describes the given vertex. """ return "VERTEX_SE2 " + (str(id) + " " + str(vert...
def reduce_by_keys(orig_dict, keys, default=None): """Reduce a dictionary by selecting a set of keys """ ret = {} for key in keys: ret[key] = orig_dict.get(key, default) return ret
def remove_comments(string_to_parse): """Remove comments following //""" string_list = string_to_parse.split("//") return string_list[0]
def generator_to_list(generator, max_count=None): """ Convert generator to list :param max_count|int: the maximum element count to be joined. """ datas = [] count = 0 for r in generator: count += 1 datas.append(r) if max_count is not None and count >...
def top_three(input_list): """Returns a list of the three largest elements input_list in order from largest to smallest. If input_list has fewer than three elements, return input_list element sorted largest to smallest/ """ input_list = sorted(input_list, reverse=True) return input_list[:3]
def _strip_fragment(url: str) -> str: """Returns the url with any fragment identifier removed.""" fragment_start = url.find('#') if fragment_start == -1: return url return url[:fragment_start]
def _getRidOfExtraChars(string): """Get rid of characters (like whitespace) that complicate string matching in input string""" #what are the characters we want to get rid of? lstOfBadChars = [' ','_',"'"] #do it using .replace() string function for i in lstOfBadChars: string = string.r...
def convert(number): """ My original and submitted solution. """ sound_mapping = { "Pling": number % 3, "Plang": number % 5, "Plong": number % 7, } return "".join([k for k, v in sound_mapping.items() if not v]) or str(number)
def build_composite_expr(query_values, entity_name, date): """Builds a composite expression with ANDs in OR to be used as MAG query. Args: query_values (:obj:`list` of str): Phrases to query MAG with. entity_name (str): MAG attribute that will be used in query. date (:obj:`tuple` of `s...
def HTMLColorToRGB(colorstring): """ convert #RRGGBB to an (R, G, B) tuple Args: colorstring (str): The string representing the color in `#RRGGBB` format Returns: tuple: A tuple of the color in (R, G, B) format Examples: >>> HTMLColorToRGB('ffff00') (255, 255, 0) ...
def nicenumber(number, binsize, lower=False): """Returns the next higher or lower "nice number", given by binsize. Examples: --------- >>> nicenumber(12, 10) 20 >>> nicenumber(19, 50) 50 >>> nicenumber(51, 50) 100 >>> nicenumber(51, 50, lower=True) 50 """ e, _ = div...
def front_replace(s, old, new): """ Return a copy of s with old replace with new in precisely one place, the front. s must start with old. """ assert s.startswith(old) return s.replace(old, new, 1)
def countBits(l): """Count the number of bits in the (long) integer l""" bits = 0 while l: l = l >> 1 bits = bits + 1 return bits
def int_to_abbrev_str(n: int): """Given an integer returns an abbreviated string representing the integer, e.g., '100K' given 100000""" if n > 0 and n % 10**6 == 0: return f'{n // 10**6}M' elif n > 0 and n % 10**3 == 0: return f'{n // 10**3}K' else: return f'{n}'
def remove_optional_type(dep_type): """if the Type is Optional[T] returns T else None :param dep_type: :return: """ try: # Hacky: an optional type has [T, None] in __args__ if len(dep_type.__args__) == 2 and dep_type.__args__[1] == None.__class__: return dep_type.__args_...
def forward_derivative(f, x, dh): """ Use the forward difference method to calculate the derivative of a function "f", evaluated at "x", using a step-size of "h" Inputs: f: A function of a variable x x: The point at which to calculate the derivative h: step size, the smaller, the more ...
def parse_slack_output(data): """Return text, channel, ts and user.""" return data["text"], data["channel"], data["ts"], data["user"]
def get_signed_headers(headers): """ Get signed headers. :param headers: input dictionary to be sorted. """ headers_to_sign = dict(headers) signed_headers = [] for header in headers: signed_headers.append(header) signed_headers.sort() return signed_headers
def binary_search(sorted_collection, item): """Pure implementation of binary search algorithm in Python Be careful collection must be sorted, otherwise result will be unpredictable :param sorted_collection: some sorted collection with comparable items :param item: item value to search :return:...
def normalizeEntities(formattedEntities): """ Normalizes the provider's entity types to match the ones used in our evaluation. Arguments: formattedEntities {List} -- List of recognized named entities and their types. Returns: List -- A copy of the input list with modified entity types....
def _check_weights(weights): """Check to make sure weights are valid""" if weights in (None, 'uniform', 'distance'): return weights elif callable(weights): return weights else: raise ValueError("weights not recognized: should be 'uniform', " "'distance', ...
def get_configuration_key(key, config, default=None): """ Look for a key in a dictionary and return if present Otherwise return the specified default :param key: String - Name of key to look for :param config: Dict - Dictionary to look for key :param default: String - The default to be returned...
def parse_production_company(movie): """ Convert production companies to a dictionnary for dataframe. Keeping only 3 production companies. :param movie: movie dictionnary :return: well-formated dictionnary with production companies """ parsed_production_co = {} top_k = 3 productio...
def get_conditions(filters): """The conditions to be used to filter data to calculate the total sale.""" conditions = "" for opts in (("company", " and company=%(company)s"), ("from_date", " and posting_date>=%(from_date)s"), ("to_date", " and posting_date<=%(to_date)s")): if filters.get(opts[0]): condition...
def _find_active_contact_using_field(value, lookup_field, match_strategy_func): """ Looks up a contact by performing a case-insensitive search on a particular field. Only non-archived contacts are considered. :param value: The value to search for :param lookup_field: The name of the field to searc...
def format_relative_comparison( part: int, total: int, ) -> str: """Format a relative comparison.""" return f"{part}/{total} ({part / total:2.2%})"
def tryGetListFromDict(d: dict, key: str): """ Gets element from dict, if not present returns empty list :param d: dict :param key: key for element :return: element or empty list """ try: return d[key] except KeyError: return []
def flatten_list(l_): """ Flattens a list Example: flatten_list([[A, B], [C]] = [A, B, C] :param l_: :return: """ return [item for sublist in l_ for item in sublist]
def generateUIDs(cids): """Generate a list of uid from a list of course ids. uid is hephen-connected ordered course id pairs. :param cids: course ids :type cids: list :return: list of unique ids :rtype: list """ uids = [] for i in range(len(cids)): for j in range(i, len(cids...
def is_wild_type(hgvs): """ This function takes an hgvs formatted string and returns True if the hgvs string indicates there was no change from the target sequence. Parameters ---------- hgvs : string hgvs formatted string Returns ------- wt : bool True if hgvs stri...
def get_changed_files(path = '.'): """ Retrieves the list of changed files. """ # not implemented return []
def _make_feature_set_descriptions(feature_sets): """ Prepare a formatted list of feature sets """ return [' {:24}{}\n'.format(cls.__name__, cls.get_description()) for cls in feature_sets] # return [' {:24}{}\n'.format(name, desc) for name, desc in feature_sets]
def pytest_ignore(cls): """ Marks the class as not-a-test-class, to prevent pytest from collecting it and reporting warnings. """ cls.__test__ = False return cls
def get_nested_fieldnames(csv_entries: dict) -> set: """Fieldnames with '.' should be converted to nested dictionaries. This function will return a set of fieldnames for nested dictionaries from the highest to second lowest levels. E.g these fieldnames: dc.date.available, dc.date.issued, dc.description ...
def has_prefix(sub_s, new_dic): """ :param sub_s: a subunit of the entered word :return: if the sub_s is the prefix of any words in the dictionary or not. """ prefix_in_word = False for word in new_dic: if word.startswith(sub_s) is True: prefix_in_word = True brea...
def diff_2(arrA, arrB): """ Runtime: O(n) """ results = [] hashA = {n: True for n in arrA} hashB = {n: True for n in arrB} for x, _ in hashA.items(): if x not in hashB: results.append(x) for x, _ in hashB.items(): if x not in hashA: results.appen...
def ServerClass(cls): """Decorate classes with for methods implementing OSC endpoints. This decorator is necessary on your class if you want to use the `address_method` decorator on its methods, see `:meth:OSCThreadServer.address_method`'s documentation. """ cls_init = cls.__init__ def __i...
def get_opposite_team(team_num): """ Returns the opposite team number """ if team_num == 2: return 3 if team_num == 3: return 2 return team_num
def format_list_as_command(params): """ Format list of items as a string. Restores the look of the parameters as they appear in command line. Used for printing error messages. Parameters ---------- params : list List of parameters to print Returns ------- str Repres...
def one_count(a, b): """ Given two adjacent indents a and b, counts how many instances of '1.' appear in b. """ lena, lenb = len(a), len(b) j = next((i for i in range(lenb) if i >= lena or a[i] != b[i]), lenb) return b[j:].count("#")
def replace_parameter_values(target_command, source_kwargs, param_mappings): """Replace the parameter values in target_command with values in source_kwargs :param target_command: The command in which the parameter values need to be replaced :type target_command: str :param source_kwargs: The source key...
def calc_t_duration(n_group, n_int, n_reset, t_frame, n_frame=1): """Calculates duration time (or exposure duration as told by APT.) Parameters ---------- n_group : int Groups per integration. n_int : int Integrations per exposure. n_reset : int Reset frames per integrat...
def tril_count_from_matrix_dim(matrix_dim: int): """Computes the number of lower triangular terms in a square matrix of a given dimension `(matrix_dim, matrix_dim)`. Args: matrix_dim (int): Dimension of square matrix. Returns: int: Count of lower-triangular terms. """ tril_count...
def parseDuration(value): """ """ if not value: return None return value.strip()
def CRRAutilityPPP(c, gam): """ Evaluates constant relative risk aversion (CRRA) marginal marginal marginal utility of consumption c given risk aversion parameter gam. Parameters ---------- c : float Consumption value gam : float Risk aversion Returns ------- (u...
def is_palindrome(string): """Function checks if passed string is palindrome.""" converted_string = str(string) rev = converted_string[::-1] if rev == converted_string: return True else: return False
def render_note(s) : """ Make rst code for a note. Nothing if empty """ return """ .. note:: %s"""%(s) if s else ''
def int16_to_bits(x): """ Unpack a 16 bit integer into binary fields. See the syntax for this here https://docs.python.org/3/library/string.html#format-specification-mini-language Parameters ---------- x : int16 single integer. Returns ------- List of binary fields alig...
def int2baseTwo(x): """x is a positive integer. Convert it to base two as a list of integers in reverse order as a list.""" # repeating x >>= 1 and x & 1 will do the trick assert x >= 0 bitInverse = [] while x != 0: bitInverse.append(x & 1) x >>= 1 return bitInverse
def parse_line(line): """ process a line, add blurb to text and return true if got to a module or function """ if line[:3] == '//!': line = line.replace('~\n', ' \n') start = 4 if line[3] == ' ' else 3 return False, line[start :] else: words = line.split() return len...
def remove_zeros(xs, ys): """Remove all instances of zeros and its' "pair" in two lists.""" new_xs, new_ys = [], [] for x, y in zip(xs, ys): if x and y: new_xs.append(x) new_ys.append(y) return new_xs, new_ys
def gcd(x, y): """greatest common divisor of x and y""" while y: x, y = y, x % y return x
def iscombinator_signature(signature): """Test if a CCG type is a combinator. A combinator expects a function as the argument and returns a function. Args: signature: The CCG signature. Returns: True if the signature is a combinator See Also: marbles.ie.ccg.cat.Category ...
def mapping_contains(self, key): """ support 'if x in y:...' """ try: self.__getitem__(key) return True except Exception: return False
def estimate_wing_passengers(FLOORS_NB, PASS_PER_TOILET, cabin_area,\ MASS_PASS, pass_density): """ The function evaluates the number of passengers members on board in case of an unconventional aircraft without fuselage. Source : passengers density is defined averaging the ...