content
stringlengths
42
6.51k
def format_val(v): """Takes in float and formats as str with 1 decimal place :v: float :returns: str """ return '{:.1f}%'.format(v)
def findSingletonWords(text): """ Splits the string |text| by whitespace and returns the set of words that occur exactly once. You might find it useful to use collections.defaultdict(int). """ # BEGIN_YOUR_CODE (our solution is 4 lines of code, but don't worry if you deviate from this) words...
def index_wn_rdf_triples(wn_rdf_triples, concept_ids, bidirectional=True): """ Retrieve related WordNet RDF triples by synset entity id. Args: wn_rdf_triples: list, contains tuples of WordNet RDF triple. concept_ids: list, contains synset concept id. bidirectional: True if select RD...
def zalpha(z, zmin, zrng, a_min=0): """ return alpha based on z depth """ alpha = a_min + (1-a_min)*(z-zmin)/zrng return alpha
def set_sample_size(n_instances): """ Determine how many instances to keep in a dataset. Side note: Why not just set the number of observations to a fixed size? """ thresholds = [(i, i * 2000) for i in range(1, 31)] for divisor, threshold in thresholds: if n_instances <= threshold: ...
def norm(v): """ :param v: vector :return: ||v|| """ return (v * v)**(1/2)
def read_docs(lines): """Pull out all documentation lines""" ret = [] on = False for line in lines: if line.lstrip().startswith('***'): if on: # just finished a block, add a new line ret.append('\n') on = not on elif on: base = "*".join...
def paths_to_edges(paths, repeat=False): """Chops a list of paths into its edges. Parameters ---------- paths: list of tuples list of the paths. repeat: bool (False) include edges repeats? Returns ------- edges: list List of edges """ edges = [] for...
def valid(x, y, passed): """ This function check if the index is in the valid area. :param x: row index of a character :param y: column index of a character :param passed: a switch used to check if a character have been visited. :return: bool """ return (0 <= x < 4) and (0 <= y < 4) and ...
def get_errno(exc): """Get exception errno (if set). Notes: :exc:`socket.error` and :exc:`IOError` first got the ``.errno`` attribute in Py2.7. """ try: return exc.errno except AttributeError: try: # e.args = (errno, reason) if isinstance(exc....
def replace_in_nested_mapping(mapping, values): """ Recursively replace "variable names" (strings that have the same value as keys in a dict) with their values in a nested 2-tuple mapping. """ definitions = {} for (mapping_key, mapping_value) in mapping: if isinstance(mapping_value, tup...
def full_palette(pal): """Extend the given palette to the full 768 bytes...""" plen = len(pal) if plen == 768: return pal newp = bytearray(768) newp[:plen] = pal[:] return newp
def adjacent_cloud(Fmask, cloud_shadow, dilatation): """ Return Fmask with all classes (adjacent cloud included). """ cloud_shadow_Fmask = cloud_shadow * Fmask dilatation_Fmask = (dilatation - cloud_shadow) * 4 other_Mask = - (dilatation - 1) remain_Fmask = other_Mask * Fmask return clou...
def _mat_2_ant(matured_rate): """Convert an matured rate to its anticipated term. :matured_rate: matured rate to be converted Uses the following equivalence: matured_rate anticipated_rate = -------------------- ( 1 + matured_rate ...
def to_int(s): """Converts safely to int. On invalid output, returns 0. Args: s: String to convert """ i = 0 try: i=int(s) except ValueError: i = 0 except TypeError: i = 0 return i
def rename_key(d, oldkey, newkey): """ Renames a key/value pair in a dictionary. Args: d: The dictionary to update. oldkey: The old key to rename. newkey: The new name of the key. Returns: The updated dictionary. """ if oldkey in d: value = d.pop(oldkey)...
def path_spliter(a_path): """ Since os.path.basename is not completely reliable when finding the basename of a directory (the user may enter it ending with a slash) so this script finds the true last directory. This function returns the name of the last branch in a directory path. """ path_sp...
def submit_run_endpoint(host): """ Utility function to generate the submit run endpoint given the host. """ return 'https://{}/api/2.0/jobs/runs/submit'.format(host)
def is_self_saved(event_list, team): """Returns whether self team had a shot that was saved""" is_true = False for e in event_list[:1]: if e.type_id == 15 and e.team == team: is_true = True return is_true
def calc_curr(lst1,lst2): """calculates current points obtained""" sum = 0 for i in range(0,len(lst1)): sum += lst1[i]*lst2[i]/100 return sum
def get_periods(start_year, end_year, duration): """Get periods over which to simulate returns. Find all continuous periods of `duration` years that fall completely between the given start and end years. Parameters ---------- start_year, end_year : int Starting and ending years. du...
def remove_dupes(iterable): """ Removes duplicate items from iterable object preserving original iterable order :param iterable: iterable :return: iterable """ unique = set() new_iter = iterable.__class__() for item in iterable: if item not in unique: new_iter.append...
def get_color_index(color,palette): """Returns the index of color in palette. Parameters: color: List with 3 int values (RGB) palette: List with colors each represented by 3 int values (RGB) Returns: Index of color in palette. -1 if not found. """ for x in rang...
def find_num(file): """used for extract the numbers from the string format file""" number = '' flag = False # used for terminating the search when meeting the last number for v in file: try: int(v) # check whether the string is number or not number += v ...
def create_stratum_name(stratification_name, stratum_name, joining_string="X"): """ generate a name string to represent a particular stratum within a requested stratification :param stratification_name: str the "stratification" or rationale for implementing the current stratification process :p...
def rectangle_intersection(a, b): """Computes intersection between two rectangles. Allows to check quickly if two bounding boxes overlap.""" x = max(a[0], b[0]) y = max(a[1], b[1]) w = min(a[0] + a[2], b[0] + b[2]) - x h = min(a[1] + a[3], b[1] + b[3]) - y if w < 0 or h < 0: return None ...
def StripNonFlags(fs): """Please rewrite this: check for desired flags instead of removing unwanted ones.""" if not fs: return [] non_flag_opts = ('-c', '-o') non_flag_args = ('-W', '-O', '-f', '-pipe', '-g', '-m') new_fs = [fs[0]] is_arg = False skip_next = False for f in fs[1:]: if skip_next: ...
def BuildArtifactSourceTree(files, file_open=open): """Builds a dependency tree using from dependency mapping files. Args: files: A comma separated list of dependency mapping files. file_open: Reference to the builtin open function so it may be overridden for testing. Returns: A dict mapping build...
def u_sum(a, *array): """ Return the submissions of array of integers -->u_sum(2, 3, 1) 6 """ result = a for ele in array: result += ele return result
def check_number_format(input_number): """ Check if value is a number. """ try: int(input_number) except ValueError: return False else: if int(input_number) <= 0: return False return True
def check_list_or_object(_list: list, _class: type): """ Checks if _list parameter is a list of the same type as _class, or if it is a single value of that type. :param _list: List or single value to be checked. :param _class: Type of object desired. :return: List of values of the type _class. "...
def maximo_ternario(a: float, b: float) -> float: """Re-escribir utilizando el operador ternario. Referencia: https://docs.python.org/3/reference/expressions.html#conditional-expressions """ return a if a > b else b
def get_time_string(total_seconds, text=False, full=False, resolution=2): """Gets either digital-clock-like time or time in plain English.""" total_seconds = int(total_seconds) values = [ #('weeks', int(total_seconds / 604800)), # Weeks are more confusing than days ('days', int(total_second...
def excel_col_name2int(s): """ >>> excel_col_name2int('A') 1 >>> excel_col_name2int('AA') 27 >>> excel_col_name2int('AB') 28 """ d = 0 for ch in s: d = d * 26 + (ord(ch) - 64) return d
def parse_version(version_string): """ Parse the version from a string The format handled is "<major>.<minor>.<patch>-<date> <commit>" Args: version_string: the version string to parse Returns: A 3-tuple of numbers: (<major>, <minor>, <patch>) """ # Remove commit from version...
def _check_history_version(history, version_string): """Check if version_string is present in history string.""" if (version_string.replace(' ', '') in history.replace('\n', '').replace(' ', '')): return True else: return False
def text_escape(s, escape='"', sep=';'): """ escapes text marks using a depth measure. """ assert isinstance(s, str) word, words = [], tuple() in_esc_seq = False for ix, c in enumerate(s): if c == escape: if in_esc_seq: if ix+1 != len(s) and s[ix + 1] != sep: ...
def interval_partitioning(events): """ Created a sorted collection of `Event(t)`, where an event can be arrival or departure, sorted based on the time. Then starting from the beginning, keep a count of `#arrival - #departure`. The max value ever encountered of `#arrival - #departure` is the answer. ...
def nested_update(defaults, updates): """ Recursively updates nested config dicts. """ if not isinstance(defaults, dict) or not isinstance(updates, dict): return updates for key, value in updates.items(): defaults[key] = nested_update(defaults.get(key, {}), value) return default...
def filter_label(label, replace_by_similar=True): """Some labels currently don't work together because of LaTeX naming clashes. Those will be replaced by simple strings.""" bad_names = [ "celsius", "degree", "ohm", "venus", "mars", "astrosun", "fullmoo...
def _round2prec(num, prec): """Don't use (directly)! Suffers from numerical precision. This function is left here just for reference. Use `round2` instead. The issue is that: >>> _round2prec(0.7,.1) 0.7000000000000001 """ return prec * round(num / prec)
def rank_dict(person_songs): """ converts a song list into a ranked song dictionary, with keys = title ranks start at 1! """ ranked_dict = {} for i in range(len(person_songs)): ranked_dict[person_songs[i]] = i + 1 return ranked_dict
def get_hex(num, digits=2): """ Convert an integer to a hex string of 'digit' characters. Args: num (int): The value to be converted. digits (int): The number of characters the final string should comprise. Default: 2. Returns: str: The hex string. """ format_str = ...
def valid_bool(boolean_str): """ Returns true if string given is a valid boolean """ if boolean_str.lower() in ['true', '1', 'false', '0']: return True return False
def getAllBeforeSpace(string): """returns all characters before a space in given string (Helper for getFirstName)""" result = '' for i in range(len(string)): if string[i] == ' ': return string[:i]
def float2(val): """type conversion""" if val is None: return 0 return float(val)
def XmlEscape(s): """Returns escaped string for the given string |s|.""" s = s.replace('&', '&amp;').replace('<', '&lt;') s = s.replace('\"', '&quot;').replace('>', '&gt;') return s
def basic_variant_dict(request): """Return a variant dict with the required information""" variant = { 'CHROM': '1', 'ID': '.', 'POS': '10', 'REF': 'A', 'ALT': 'C', 'QUAL': '100', 'FILTER': 'PASS', 'FORMAT': 'GT', 'INFO': '.', 'info...
def sum_to_n(n: int) -> int: """ >>> sum_to_n(0) 0 >>> sum_to_n(1) 1 >>> sum_to_n(2) 3 >>> sum_to_n(10) 55 >>> sum_to_n(100) 5050 """ return (1 + n) * n // 2
def is_numeric(value): """Checks if value is of type Numeric Keyword arguments: value -- The object to be checked Returns True if - value is of type int - value is of type float - value is of type complex Else it returns False. (Note that "Booleans are a subtype of ...
def checksum(number): """Calculate the checksum over the number.""" # replace letters by their ASCII number return sum(int(x) if x.isdigit() else ord(x) for x in number) % 9
def _filter_domain_id_from_parents(domain_id, tree): """Removes the domain_id from the tree if present""" new_tree = None if tree: parent, children = next(iter(tree.items())) # Don't add the domain id to the parents hierarchy if parent != domain_id: new_tree = {parent: _f...
def to_id(s): """Covert text to ids.""" if s == "+": return 11 if s == "*": return 12 return int(s) + 1
def set_column_hidden_attribute(column_limit, columns): """Sets the hidden attribute on columns higher than the column_limit. Args: column_limit (int) The number of columns that can be displayed. columns (list of Column) A list of columns. """ if len(columns) <= column_limit: retu...
def parse_values_in_lines(lines): """ Parses the lines for 'A = B' lines and returns a dictionary, as well as the profile name """ values = {} profile_name = None for line in lines: line = line.strip() if len(line) > 2 and line[0] == '[': profile_name = line[1:-1]...
def is_query(line: str) -> bool: """ Return True, if provided line embeds a query, else False """ return "@SQLALCHEMY" in line and "|$" in line
def Diffs(t): """List of differences between the first elements and others. t: list of numbers returns: list of numbers """ first = t[0] rest = t[1:] diffs = [first - x for x in rest] return diffs
def listrange2dict(L): """ Input: a list Output: a dictionary that, for i = 0, 1, 2, . . . , len(L), maps i to L[i] You can use list2dict or write this from scratch """ return {i: L[i] for i in range(len(L))}
def splitdate(yyyymmddhh): """ yyyy,mm,dd,hh = splitdate(yyyymmddhh) give an date string (yyyymmddhh) return integers yyyy,mm,dd,hh. """ yyyy = int(yyyymmddhh[0:4]) mm = int(yyyymmddhh[4:6]) dd = int(yyyymmddhh[6:8]) hh = int(yyyymmddhh[8:10]) return yyyy,mm,dd,hh
def parse_name ( name ): """ Parses a possible compound data context name. """ return name.split( '.' )
def tempo(msg): """Returns the usec tempo value from a tempo meta message.""" return (msg[3] << 16) + (msg[4] << 8) + msg[5]
def isIn(char, aStr): """ :param char: a single character :param aStr: an alphabetized string :return: True if char is in aStr; False otherwise """ def binary_search(aStr,low, high, char): if high > low: ans = (high + low) // 2 if char == aStr[ans]: ...
def GetLightClr(idx=0, scheme=1): # color """ Get ordered light color ======================= """ #if scheme==1: C = ['#64f1c1', '#d2e5ff', '#fff0d2', '#bdb6b9', '#a6c9b7', '#c7c9a6', '#a6a6c9', '#c9a6bf', '#de9700', '#89009d', '#7ad473', '#737ad4', '#d473ce', '#7e6322', '#462222', '#98acdd', '#...
def escape_bytes(value7_uint64be): """Escapes seven bytes to eight bytes. Args: value7_uint64be(int): Bytes as a 56-bit bigendian unsigned integer. Returns: int: Escaped bytes as a 64-bit bigendian unsigned integer. """ x = value7_uint64be x0 = x & 0x000000000FFFFFFF x1 = x ...
def numeric_range(numbers): """ Returns the difference between largest and smallest of given numbers. """ try: iterator = iter(numbers) maximum = minimum = next(iterator) except StopIteration: maximum = minimum = 0 for number in numbers: if number > maximum: ...
def address_to_reverse(address): """Take the address and construct the reverse lookup format.""" return '{}.in-addr.arpa'.format('.'.join(reversed(address.split('.'))))
def remove_prefix(text, prefix): """ Removes given prefix from text, returns stripped text. Args: text(str): text to remove prefix from prefix(str): prefix to remove from text Returns: (str) stripped text """ if text.startswith(prefix): return text[len(prefix):] r...
def literal_value(pkt): """ >>> literal_value(h2b(read_input('ex1'))) (2021, 21) >>> literal_value('11010001010') (10, 11) """ loc = 6 binstr = "" while pkt[loc] == "1": binstr += pkt[loc + 1 : loc + 5] loc += 5 return int(binstr + pkt[loc + 1 : loc + 5], 2), loc ...
def parse_hal_spikes(hal_spikes): """Parses the tag information from the output of HAL Parameters ---------- hal_spikes: output of HAL.get_spikes() (list of tuples) Returns a nested dictionary: [pool][neuron] = list of (times, 1) tuples The 1 is for consistency with the return of p...
def convertDNA(sequence): """ Input a DNA sequence as a string. Output a string with the sequence mapped to binary.""" sequence = sequence.replace('A', '0001') sequence = sequence.replace('C', '0010') sequence = sequence.replace('G', '0100') sequence = sequence.replace('T', '1000') return sequen...
def check_reformat_versions(ctx, buffer, committed, last_site_action, successful_site_action): """Checks and reformat version""" versions = [] if buffer: versions.append('buffer') if committed: versions.append('committed') if last_site_action: ver...
def generate_backlinks(thread_dict): """Generates backlinks to posts based on the quotes in post_dicts of thread_dict :param thread_dict: Dict containing keys of postnrs and fileurls with post_dict as values""" for key, post_dict in thread_dict.items(): if "/" in key: # key is fileurl ...
def get_divided_long_message(text, max_size): """ Cuts long message text with \n separator @param text: str - given text @param max_size: int - single text message max size return: text part from start, and the rest of text """ subtext = text[:max_size] border = subtext.rfind('\n') ...
def choose_template(key): """ - Fetch the template considering the provided key - Returns a template to be filled using f-string """ template={} template["postgres"] = "host={DATABASE_IP_ADDRESS} dbname={DATABASE_NAME} user={DATABASE_USERNAME} password={DATABASE_PASSWORD}" template[...
def merge_two_dicts(a, b): """Merge two dicts into one dict, with the second overriding.""" d = a.copy() d.update(b) return d
def process(container_, search_element_) -> int: """ Search the container for the element. :param container_: The list of elements :param search_element_: The element to search :return: return position of the element. """ position = 0 iteration = 0 while position < len(container_): ...
def _ogroups_to_odict(ogroups, swap_order=False): """ From a list of orthogroups, return a dict from sp1 prots to a set of sp2 prots. We want a dictionary from the first species in the file to the second, unless swap_order is True. """ sp1col = 1 if swap_order else 0 sp2col = 0 if swap_ord...
def remove_entity_from_list(unique_list, i): """ Removes all instances of a particular entity from a list >>> remove_entity_from_list(['test', 'test', 'three'], 1) ['three'] """ return [x for x in unique_list if x != unique_list[i]]
def romaine_v1(string): """ (str) -> int Converts roman numerals to arabic numerals using string methods. Restrictions: string must consist of M, D, C, X, V, and/or I. Otherwise it will return 0 (which is to be expected anyway). """ string = string.strip() string = string.lower() no...
def abridged_list(items): """Return the list of items abridged. Example given: [1, 2, 3, 4, 5] return: [1, 2, '...', 5] """ if len(items) <= 4: return items snipped = items[0:2] snipped.append('...') snipped.append(items[-1]) return snipped
def isindex(str): """True if a string is something we can index an array with.""" try: int(str) return True except ValueError: return False
def find_storage_value(buffer: bytes, index: int) -> bytes: """ find_value """ num_of_unit8 = int.from_bytes(buffer[0 : 4], 'big') num_of_unit16 = int.from_bytes(buffer[4 : 8], 'big') num_of_unit32 = int.from_bytes(buffer[8 : 12], 'big') len_of_vals_start_pointer = 12 vals_pointer = len_of_vals_...
def make_prev_next(seg_table): """ Function to make two column table into a four column table with prev/next seg :param seg_table: Input table of form: They They don't do|n't know know :return: Four column table with prev/next group context columns: _ don't They They They know don...
def pentagonal(number): """ Returns True if number is pentagonal """ n = 1 while True: p = n * (3 * n - 1) / 2 if p == number: return True elif p > number: return False n = n + 1
def make_album(artist, title, tracks = 0): """Build a dictionary containing information about an album.""" album_dictionary = {'artist' : artist.title(), 'title' : title.title()} if tracks: album_dictionary['tracks'] = tracks return album_dictionary
def _is_batched(obj) -> bool: """ N.B. This function cannot be imported from quantify_core.measurement.type due to some circular dependencies that it would create in the quantify_core.measurement.__init__ Returns ------- : The `.batched` attribute of the settable/gettable `obj`, `Fa...
def cumple_normativa(tiempo, descanso): """ Decide si los criterios establecidos para un determinado examen pasan la normativa o no. @param tiempo: tiempo en horas @param descanso: booleano que define si hay descanso o no @return: True si se cumple la normativa. False en caso contrar...
def ndwi_gao(b8, b11): """ Normalized Difference Water Index (Gao, 1996). .. math:: NDWI = (b8 - b11)/(b8 + b11) :param b8: NIR. :type b8: numpy.ndarray or float :param b11: SWIR 1. :type b11: numpy.ndarray or float :returns NDWI: Index value .. Tip:: Gao, B. 1996. NDWI ...
def parse_str_as_list(s: str) -> list: """Produces a list from its string representation. Runs `eval` on non-list elements within Args: s (str): a string representing a list Returns: list: a list containing elements from **s** """ def try_eval_str(t): try: ...
def _sanitize_op_name(op_name): """ Sanitize the op name - ignore '^' character of control input """ if op_name.startswith('^'): return op_name[1:] return op_name
def inspect_chain(chain): """Return whether a chain is 'GOOD' or 'BAD'.""" next_key = chain.pop('BEGIN') while True: try: next_key = chain.pop(next_key) if next_key == "END": break except KeyError: return "BAD" if len(chain) > 0: ...
def remove_build_suffix(version): """Remove build suffix (if exists) from a version.""" if version.find("-dev") >= 0: return version[:version.find("-dev")] if version.find(".dev") >= 0: return version[:version.find(".dev")] if version.find("dev") >= 0: return version[:version.find("dev")] return v...
def ecorr_basis_prior(weights, log10_ecorr=-8): """Returns the ecorr prior. :param weights: A vector or weights for the ecorr prior. """ return weights * 10**(2*log10_ecorr)
def remove_suffix(string, suffix): """ This function removes the given suffix from a string, if the string does indeed end with the prefix; otherwise, it returns the string unmodified. """ # Special case: if suffix is empty, string[:0] returns ''. So, test # for a non-empty suffix. if su...
def _analyze_cython_code(code_lines): """ Find the position of classes and functions in *Cython* files. This analyzer works in a very simple way: It looks for the `def` and `class` keywords at zero-indentation level and determines the end of a class/function by the start of the next zero-indent...
def parse_opcode(code): """Each opcode is up to 5 digits long. The two on the furthest right contain the instruction, and then the 3 on the left (reading from right to left) indicate the mode (position or immediate) for each of the parameters. This function converts the number to a 0 padded string ...
def broadcast_shape(*shapes, **kwargs): """ Similar to ``np.broadcast()`` but for shapes. Equivalent to ``np.broadcast(*map(np.empty, shapes)).shape``. :param tuple shapes: shapes of tensors. :param bool strict: whether to use extend-but-not-resize broadcasting. :returns: broadcasted shape ...
def find_all(tofind, string): """Returns number of times a certain substring is found""" found = [i for i in range(len(string)) if string.startswith(tofind, i)] num_found = len(found) return num_found
def decode_free_output(value): """Decodes the output value when found free (without the 'output' keyword)""" try: return "output", {"port": int(value)} except ValueError: return "output", {"port": value.strip('"')}
def run_program(program: list) -> int: """Execute an Intcode program :param program: Intcode program :return: Output of the Intcode program """ for i in range(len(program) // 4 + 1): opcode = program[4 * i] if opcode == 99: break pos1, pos2, pos3 = program[(4 * i...