content
stringlengths
42
6.51k
def build_filename_data(_bibcode:str) -> str: """ Builds the name for the data output file """ return '{}.json'.format(_bibcode)
def get_item(dictionary, key): """Returns value corresponding to a certain key in a dictionary. Useful if standard 'dot-syntax' lookup in templates does not work. """ return dictionary.get(key)
def eformat(f, prec, exp_digits): """ Formats to Scientific Notation, including precise exponent digits """ s = "%.*e" % (prec, f) mantissa, exp = s.split("e") # add 1 to digits as 1 is taken by sign +/- return "%sE%+0*d" % (mantissa, exp_digits + 1, int(exp))
def landeg(gL,gS,J,S,L): """ Calculating the Lande factor g, For fine structure: landeg(gL,gS,J,S,L) For hyperfine structure: landeg(gJ,gI,F,I,J) """ return gL * (J * (J + 1) - S * (S + 1) + L * (L + 1)) / (2 * J * (J + 1)) + \ gS * (J * (J + 1) + S * (S + 1) - L * (L + 1)) / (2...
def recalculateEnergies(d, grid_number, min_energy, delta): """ For each density sample, we want the same exponential energy grid :param d: :param grid_number: :param min_energy: :param delta: :return: """ densities = d.keys() new_energies = [] for i in range(0, grid_number):...
def stress_score(norm_power, threshold_power, duration): """Stress Score Parameters ---------- norm_power : number NP or xPower threshold_power : number FTP or CP duration : int Duration in seconds Returns ------- ss: TSS or BikeScore ...
def urljoin(*args): """ Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument. https://stackoverflow.com/a/11326230 """ return "/".join(map(lambda x: str(x).strip('/').rstrip('/'), args))
def get_curated_date(date): """ remove the seconds etc, e.g., 2018-07-15T16:20:55 => 2018-07-15 """ return date.strip().split('T')[0]
def merge_dicts(dicts): """ Keep updating one dict with the values of the next """ result = {} for item in dicts: result.update(item) return result
def get_package_repo_name(package_info): """ The source repo name is stored with the package. The "From repo" line indicates where the package came from. Return the repo name or None if not found """ # should check that there is EXACTLY one line repo_lines = \ [line for line in pac...
def distance(strand_a, strand_b): """Determine the hamming distance between two RNA strings param: str strand_a param: str strand_b return: int calculation of the hamming distance between strand_a and strand_b """ if len(strand_a) != len(strand_b): raise ValueError("Strands must be of eq...
def xor(msg: bytes, key: bytes, strict: bool = False) -> bytes: """ XOR encrypts/decrypts a message :param msg: Message to encrypt/decrypt :type msg: bytes :param key: Key to use :type key: bytes :param strict: If encrypting and this is set to True, the key MUST be at least as long as the m...
def validate_input(input_string): """ :param str input_string: A string input to the program for validation that it will work wiht the diamond_challenge program. :return: *True* if the string can be used to create a diamond. *False* if cannot be used. """ if not isinstance(input_string, st...
def stripiter(target: list): """Striping all of texts in list.""" out = [] for txt in target: out.append( str(txt) .rstrip() .lstrip() ) return out
def sort_font(fontlist): """ Returns a new list that is first sorted by the font's compatibleFamilyName3 (Windows compatible name), and secondly by the font's macStyle (style name). """ return sorted(fontlist, key=lambda font: (font.compatibleFamilyName3, font.macStyle))
def fix_single_tuple(x): """For scalar x, return x. For 1 element tuple, return x[0]. For multi-element tuple, return x. """ if isinstance(x, tuple): if len(x) == 1: return x[0] return x
def sum_digits(y): """Sum all the digits of y. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 >>> a = sum_digits(123) # make sure that you are using return rather than print >>> a 6 """ result = 0 cur = 0 ...
def _BuildOutputFilename(filename_suffix): """Builds the filename for the exported file. Args: filename_suffix: suffix for the output file name. Returns: A string. """ if filename_suffix is None: return 'results.html' return 'results-{}.html'.format(filename_suffix)
def compare_strings(first, second): """Compare two strings, returning the point of divergence and the equality""" big = max(len(first), len(second)) small = min(len(first), len(second)) if big == small: pairs = [(x,y) for x, y in zip(first, second)] else: pairs = [(x,y) for i, (x, y)...
def argument(*name_or_flags, **kwargs): """Convenience function to properly format arguments to pass to the subcommand decorator.""" return (list(name_or_flags), kwargs)
def _filter_none_values(d: dict): """ Filters out the key-value pairs with None as value. Arguments: d dictionary Returns: filtered dictionary. """ return {key: value for (key, value) in d.items() if value is not None}
def oddNumbers(l, r): """ List odd numbers within a closed interval. :param l: left interval endpoint (inclusive) :param r: right interval endpoint (inclusive) :return: odd numbers within [l, r]. """ l = l if l % 2 == 1 else l + 1 r = r if r % 2 == 0 else r + 1 return list(range(l, r, 2))
def filter_none(d) : """ Remove items of a dictionary with None values. Args: d (:obj:`dict`): Dictionary object. Returns: :obj:`dict`: Dictionary without None items. """ if isinstance(d, dict) : return {k: filter_none(v) for k,v in d.items() if v is not None} elif ...
def filesize(file): """ Returns the size of file sans any ID3 tag """ f=open(file) f.seek(0,2) size=f.tell() try: f.seek(-128,2) except: f.close() return 0 buf=f.read(3) f.close() if buf=="TAG": size=size-128 if size<0:...
def order_domain(var, assignment, board): """order domain""" if (len(assignment) <= 1): return assignment cons_lev = {} for i in assignment: cons_lev[i] = 0 for v in board.values(): if v in assignment: cons_lev[v] =+ 1 ...
def add_vectors(vector_1, vector_2): """Example function. Sums the same index elements of two list of numbers. Parameters ---------- v1 : list List of ints or floats v2 : list List of ints or floats Returns ------- list Sum of lists Notes ----- Thi...
def get_next_level_groups(groups): """ Find all groups of k+1 elements such that all of their subgroups with k elements are given. Parameters ---------- groups: array of sorted touples - all valid groups of (indicies f) k detections identifies so far Returns ------- array of sorted tou...
def _split_path(loc): """ Split S3 path into bucket and prefix strings """ bucket = loc.split("s3://")[1].split("/")[0] prefix = "/".join(loc.split("s3://")[1].split("/")[1:]) return bucket, prefix
def doubled_label_fix(lbls, num, previous): """ Fix ground truth mix up where a sentence belogns to two sections in a report. :param lbls: The two labels that are confusing. :param num: The sentence number in the report :param previous: previous sentence label :return: The correct label to u...
def abstract_injection_type(assignment): """ return an abstract type name for the type we have in the given assignment. """ if "[" in assignment["type"]: return "array" if not any(c in assignment["type"] for c in "[](){}"): return "scalar" return None
def is_product_id(identifier): """Check if a given identifier is a product identifier as opposed to a legacy scene identifier. """ return len(identifier) == 40
def inclusion_two_params_from_template(one, two): """Expected inclusion_two_params_from_template __doc__""" return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)}
def ifnone(*xs): """Return the first item in 'x' that is not None""" for x in xs: if x is not None: return x return None
def path_from_query(query): """ >>> path_from_query('/service?foo=bar') '/service' >>> path_from_query('/1/2/3.png') '/1/2/3.png' >>> path_from_query('foo=bar') '' """ if not ('&' in query or '=' in query): return query if '?' in query: return query.split('?', 1)[...
def get_8_bit_fg_color(r, g, b): """Returns the color value in the 6x6x6 color space. The other color values are reserved for backwards compatibility""" return '38;5;%d' % (16 + 36 * r + 16 * g + b)
def can_run_for_president(age): """Can someone of the given age run for president in the US?""" # The US Constitution says you must be at least 35 years old return age >= 35
def accuracy_score(y_true, y_pred): """Accuracy classification score. In multilabel classification, this function computes subset accuracy: the set of labels predicted for a sample must *exactly* match the corresponding set of labels in y_true. Args: y_true : 2d array. Ground truth (correct)...
def get_device(config): """ Return the device portion of the part Device portion of an example: xc6slx9-tqg144-3: xc6slx9 Args: config (dictionary): configuration dictionary Return: (string) device Raises: Nothing """ part_string = config["device"] de...
def square_sorted(A): """Given a sorted array, return a new array sorted by the squares of the the elements. [LC-977] Example: >>> square_sorted([-4, -1, 0, 3, 10]) [0, 1, 9, 16, 100] >>> square_sorted([-7, -3, 2, 3, 11]) [4, 9, 9, 49, 121] >>> square_sorted([-2, -1, 0, 2, 3]) ...
def split_lists(original_list, max_slices): """ Split a list into a list of small lists given the desired number of sub lists """ slices = max_slices - 1 original_list_size = len(original_list) split_index = int(original_list_size / slices) return [original_list[x:x + split_index] for x in range(0, ...
def in_range(value, minimum, maximum): """Check if value is in range.""" okay = True if minimum >= 0 and value < minimum: okay = False elif maximum >= 0 and value > maximum: okay = False return okay
def jump(orig): """encipher the plain text num""" encoding = {'0': '5', '5': '0', '1': '9', '2': '8', '3': '7', '4': '6', '6': '4', '7': '3', '8': '2', '9': '1'} cipher = encoding[orig] return cipher
def _tile2lng(tile_x, zoom): """Returns tile longitude Parameters ---------- tile_x: int x coordinate zoom: int zoom level Returns ------- longitude """ return ((tile_x / 2 ** zoom) * 360.0) - 180.0
def parse_csv_header(line): """Parse the CSV header returned by TDS.""" units = {} names = [] for var in line.split(','): start = var.find('[') if start < 0: names.append(str(var)) continue else: names.append(str(var[:start])) end = var...
def _near_words( first: str, second: str, distance: int, exact: bool = False ) -> str: """ Returns a query term matching messages that two words within a certain distance of each other. Args: first: The first word to search for. second: The second word to search for. ...
def sp(number, singular, plural): """ Return either a singular or plural form of a noun based on a number. """ return singular if number == 1 else plural
def resolve_checks(names, all_checks): """Returns a set of resolved check names. Resolving a check name involves expanding tag references (e.g., '@tag') with all the checks that contain the given tag. names should be a sequence of strings. all_checks should be a sequence of check classes/instance...
def testfn(arg): """ Test function for L{deferred} decorator. Raises L{ValueError} if 42 is passed, otherwise returns whatever was passed. """ if arg == 42: raise ValueError('Oh noes') return arg
def check_keys_contain(result_keys, target_keys): """Check if all elements in target_keys is in result_keys.""" return set(target_keys).issubset(set(result_keys))
def valid_type(data): """ >>> valid_type(0.1) True >>> valid_type(1) True >>> valid_type("hola") False >>> valid_type([1, 2]) False """ return type(data) in [int, float]
def breadcrumbs_li(links): """Returns HTML: an unordered list of URLs (no surrounding <ul> tags). ``links`` should be a iterable of tuples (URL, text). """ crumbs = '' li_str = '<li><a href="{}">{}</a></li>' li_str_last = '<li class="active"><span>{}</span></li>' # Iterate over the list, exc...
def sat_proportional_filter( input: float, abs_min=0.0, abs_max=10.0, factor=1) -> float: """ Simple saturated proportional filter :param input : input value :param abs_min and abs_max : upper and lower bound, abs value :param factor : multiplier factor for the ...
def n_to_data(n): """Convert an integer to one-, four- or eight-unit graph6 sequence. This function is undefined if `n` is not in ``range(2 ** 36)``. """ if n <= 62: return [n] elif n <= 258047: return [63, (n >> 12) & 0x3F, (n >> 6) & 0x3F, n & 0x3F] else: # if n <= 687194767...
def _rotate_byte(byte, rotations): """Rotate byte to the left by the specified number of rotations.""" return (byte << rotations | byte >> (8-rotations)) & 0xFF
def list_videos(plugin, item_id, category_url, **kwargs): """Build videos listing""" return False # videos_json = urlquick.get(URL_PLAYLIST % category_playlist).text # videos_jsonparser = json.loads(videos_json) # for video_data in videos_jsonparser["videos"]: # item = Listitem() # ...
def handle_result(api_dict): """Extract relevant info from API result""" result = {} for key in {"title", "id", "body_safe", "locale", "section"}: result[key] = api_dict[key] return result
def n_choose_k(n: int, k: int) -> int: """ Calulate the number of combinations in N choose K When K is 0 or 1, the answer is returned directly. When K > 1, iterate to compute factoral to compute nCk formula = n! / (k! (n-k)! by using m as an accumulator :return: number of ways to choose k from n ...
def lookupDict(item_list, keyprop="key_string", valueTransform=None): """ keyprop can be 'key_string', 'key_id', or a property name if valueProp is None, value at each key is full item from list otherwise, run specified function to get value to store in dict """ lookup = {} for item in item_...
def evenify(num, oddify=False): """ Make sure an int is even... or false returns: type int """ if oddify: remainder = 1 else: remainder = 0 if num % 2 == remainder: return num else: return num + 1
def get_file_or_default(metric_file): """ Returns the module name from which to extract metrics. Defaults to cohorts.metrics :param str metric_file: The name of the module to extract metrics from :return: The name of the module where metric functions reside """ return metric_file if metric_file is...
def find_choice_index(choice, choices): """ Finds the index of an item in a choice list. """ for choice_tuple in choices: if choice == choice_tuple[1]: return choice_tuple[0] - 1
def validateSyntax(func): """ Check if the function is valid. Arguments: function Warning: This function only checks if the function stays in the syntax limit. Further validation will be conducted later when an error is thrown. """ validSyntax = 'abcdefghijklmnopqrstuvwxz1234567890()+-...
def to_arcmin(crosshair, origin, pixels_per_arcmin): """Convert the crosshair location from pixels to arcmin. Parameters ---------- crosshair : :class:`dict` The location of the crosshair. origin : :class:`dict` The location of the origin. pixels_per_arcmin : :class:`float` ...
def floating_point(v): """ Is arg a floating point number ? """ return isinstance(v, float)
def merge(b, c): """ Arguments: Array1, Array2: Two sorted arrays b and c. Return: array_d: The merged version of b and c """ i = 0 j = 0 k = 0 n1 = len(b) n2 = len(c) array_d = [None]*(n1+n2) # traverse both arrays while i<n1 and j<n2: ...
def _count_relative_level(module_symbol: str) -> int: """Given a relative package name return the nested levels based on the number of leading '.' chars Args: module_symbol (str): relative module symbol Returns: int: relative import level """ module_symbol_cp = str(module_symbol) ...
def concat_and_filters(filters): """Task for an AND filter list For more information see the API documentation :param filters: the filter list to be concat :type filters: List :return: A Json filter formated :rtype: Dict """ return {"operator": "And", "filters": filters}
def _normalize_padding(padding): """Ensure that padding has format (left, right, top, bottom, ...)""" if all(isinstance(p, int) for p in padding): return padding else: npadding = [] for p in padding: if isinstance(p, (list, tuple)): npadding.extend(p) ...
def includes_subpaths(path) : """Checks if a given path includes subpaths or not. It includes them if it ends in a '+' symbol. """ return path[-1] == '+'
def miller_rabin(n): """ primality Test if n < 3,825,123,056,546,413,051, it is enough to test a = 2, 3, 5, 7, 11, 13, 17, 19, and 23. Complexity: O(log^3 n) """ if n == 2: return True if n <= 1 or not n & 1: return False primes = [2, 3, 5, 7, 11, 13, 17, 19,...
def strtobool(val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in ("y", "ye...
def isAbsolute(uri : str) -> bool: """ Check whether a URI is Absolute. """ return uri is not None and uri.startswith('//')
def floatformat(number, mind=2, maxd=4): """ Format a floating point number into a string """ rounded = int(number * (10**mind)) / float(10**mind) if number == rounded: return ('%%.0%df' % mind) % number else: return ('%%.0%dg' % maxd) % number
def query_decode(query): # type: (str) -> str """Replaces "+" for " " in query""" return query.replace("+", " ")
def is_internal_mode(alignment_set, is_legacy): """See if alignmentset was collected in internal-mode.""" if is_legacy: is_internal = True else: is_internal = 'PulseCall' in alignment_set.pulseFeaturesAvailable() return is_internal
def unique(iterable): """Uniquify elements to construct a new list. Parameters ---------- iterable : collections.Iterable[any] The collection to be uniquified. Returns ------- list[any] Unique elements as a list, whose orders are preserved. """ def small(): ...
def flat(l): """ Parameters ---------- l : list of list Returns ------- Flattened list """ return [item for sublist in l for item in sublist]
def filter_uniq(item): """Web app, feed template, creates unique item id""" detail = item['item'] args = (item['code'], item['path'], str(detail['from']), str(detail['to'])) return ':'.join(args)
def validate_main_menu(user_input): """Validation function that checks if 'user_input' argument is an int 1-4. No errors.""" switcher = { 1: (True, 1), 2: (True, 2), 3: (True, 3), 4: (True, 4), 5: (True, 5), 6: (True, 6) } return switcher.get(user_input, (...
def least_distance_only(annotation, new_annotations): """Condition function to keep only smallest distance annotation per image Args: annotation: Current annotation being examined new_annotations: Dict of new annotations kept by image_name Returns: True if annotation image is not yet in ne...
def normalize_dict(dictionary: dict, dict_sum: float) -> dict: """ Constrain dictionary values to continous range 0-1 based on the dictionary sum given. Args: - dictionary: the dictionary to be normalized. - dict_sum: the sum value to normalize with. """ return {key: value/d...
def pick_from_greatests(dictionary, wobble): """ Picks the left- or rightmost positions of the greatests list in a window determined by the wobble size. Whether the left or the rightmost positions are desired can be set by the user, and the list is ordered accordingly. """ previous = -100 is...
def conv_bright_ha_to_lib(brightness) -> int: """Convert HA brightness scale 0-255 to library scale 0-16.""" if brightness == 255: # this will end up as 16 which is max brightness = 256 return int(brightness / 16)
def get_sorted_data(data: list, sort_by: str, reverse=True) -> list: """Get sorted data by column and order Parameters ---------- data : list Data stored in list of dicts sort_by : str Sort data by specific column reverse : bool, optional Flag to determinate order of sor...
def dimensions(rotor_lst): """ Get the dimensions of each of the rotors """ return tuple(len(rotor) for rotor in rotor_lst)
def find_smallest(arr): """Find Smallest value in an array.""" smallest = arr[0] smallest_i = 0 for i, val in enumerate(arr): if val < smallest: smallest = val smallest_i = i return smallest_i
def stage_check(x): """A simple function to chack if a string contains keyword '2'""" import re if re.compile('2',re.IGNORECASE).search(x): return True else: return False
def join_slices(*slices): """Join together contiguous slices by extending their start and/or end points. All slices must be increasing, i.e. start < stop. Identical slices will be removed. Args: *slices (iterable of slice): Slices to concatenate. Examples: >>> join_slices(slice(0,...
def add_article ( name ): """ Returns a string containing the correct indefinite article ('a' or 'an') prefixed to the specified string. """ if name[:1].lower() in 'aeiou': return 'an ' + name return 'a ' + name
def is_chinese(name): """ Check if a symbol is a Chinese character. Note ---- Taken from http://stackoverflow.com/questions/16441633/python-2-7-test-if-characters-in-a-string-are-all-chinese-characters """ if not name: return False for ch in name: ordch = ord(ch) ...
def deg2HMS(ra=None, dec=None, round=False): """ quick and dirty coord conversion. googled to find bdnyc.org. """ RA, DEC, rs, ds = '', '', '', '' if dec is not None: if str(dec)[0] == '-': ds, dec = '-', abs(dec) deg = int(dec) decM = abs(int((dec-deg)*60)) i...
def codify(in_str: str) -> str: """ Cushions a string with four "`" character, used to indicated code in a Sphinx rst file. :param in_str: The string to cushion :return: The cushioned string """ return "``{}``".format(in_str)
def levenshtein_distance(w1, w2): """ Parameters: ---------- w1: str w2: str Returns: -------- int: Returns Levenshtein edit distance between the two strings """ n1 = len(w1) + 1 n2 = len(w2) + 1 dist = [[0]*n2 for _ in range(n1)] for i in range(n1): ...
def contain_any(iterable, elements): """ Return `True` if any of the `elements` are contained in the `iterable`, `False` otherwise. """ for e in elements: if e in iterable: return True return False
def lowercase(string): """Convert string into lower case. Args: string: String to convert. Returns: string: Lowercase case string. """ return str(string).lower()
def _query_builder(parameters): """Converts dictionary with queries to http-able query.""" queries = dict() for key in parameters: queries.setdefault(key, set()) if type(parameters[key]) in [list, set]: # Union is Set.extend() in this context. queries[key] = queries[k...
def link(url, linkText='{url}'): """Returns a link HTML string. The string is an &lt;a&gt; tag that links to the given url. If linkText is not provided, the link text will be the url. """ template = '<a href={url}>' + linkText + '</a>' return template.format(url=url)
def check_proxy(host, port): """ Is there even an appearance of something resembling a proxy on the set up port? """ if host is None or port is None: print("No proxy set up at options.yaml") return False import socket with socket.socket() as proxy: try: pro...
def removeDuplicateEntries(outputList): """ Take a list of entries (dictionaries), and create a new list where duplicate entries have been omitted. The basis for detecting duplication is the esaId key. """ newOutputList = [] esaIdSet = set() for entry in outputList: esaId = ent...
def get_pos_colors(image, x, y): """Get the color at a position or 0-vector, if the position is invalid.""" if x > 0 and y > 0 and len(image) > y and len(image[0]) > x: return (image[y][x][0], image[y][x][1], image[y][x][2]) else: return (0, 0, 0)