content
stringlengths
42
6.51k
def rest(s): """Return all elements in a sequence after the first""" return s[1:]
def instances_security_groups(instances): """ Return security groups associated with instances. :param instances: list of ec2 instance objects :type instances: list :return: list of dicts with keys GroupId and GroupName :rtype: list """ # we turn the groups into frozensets to make them ...
def parse_dist_text(text: str) -> float: """ """ try: return float(text[:-3]) except ValueError: for i in range(0, -11, -1): try: return float(text[:i]) except ValueError: continue else: raise ValueEr...
def factorial_r(number): """ Calculates the factorial of a number, using a recursive process. :param number: The number. :return: n! """ # Check to make sure the argument is valid. if number < 0: raise ValueError # This is the recursive part of the function. if number == 0...
def set_config_var(from_file, from_env, default): """ Set a configuration value based on the hierarchy of: default => file => env :param from_file: value from the configuration file :param from_env: value from the environment :param default: default configuration value :return: value to...
def rwh_primes1(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Returns a list of primes < n """ sieve = [True] * (n // 2) for i in range(3, int(n ** 0.5) + 1, 2): if sieve[i // 2]: sieve[i * i // 2 :: i] = [False...
def get_imageurl(img): """Get the image url helper function.""" result = 'https://www.buienradar.nl/' result += 'resources/images/icons/weather/30x30/' result += img result += '.png' return result
def prev_heart_rate(patient): """Gives list of all posted heart rates for a patient Method curated by Braden Garrison The accepted patient database is analyzed to produce a list of all previously posted heart rates for that patient. Args: patient (dict): accepts patient dict containing al...
def add_default_module_params(module_parameters): """ Adds default fields to the module_parameters dictionary. Parameters ---------- module_parameters : dict Examples -------- >> module = add_default_module_params(module) Returns ------- module_parameters : dict ...
def add_arrays(x, y): """ This function adds together each element of the two passed lists. Args: x (list): The first list to add y (list): The second list to add Returns: list: the pairwise sums of ``x`` and ``y``. Examples: >>> add_arrays([1, 4, 5], [4, 3, 5]) ...
def reformat_prop(obj): """ Map over ``titles`` to get properties usable for looking up from node instances. Change properties to have 'node_id' instead of 'id', and 'label' instead of 'type', so that the props can be looked up as dictionary entries: .. code-block:: python node[pr...
def objective_function(x, y, name="rosenbrock"): """Return value of the objective function at coordinates x1, x2.""" if name == "rosenbrock": return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2 else: raise NotImplementedError
def getPathToGoal(start, goal, parents): """Given the hash of parental links, follow back and return the chain of ancestors.""" try: results = [] while (goal != start): results.append(goal) goal = parents[goal] # end while (goal != start) results.append(start) results.reverse() return results exce...
def list2str(lst, short=True): """ Returns a string representing a list """ try: if short: return ', '.join(lst) else: return str(lst) except: if short: return "" else: return "[]"
def get_nextupsegs(graph_r, upsegs): """Get adjacent upsegs for a list of segments as a single flat list. Parameters ---------- graph_r : dict Dictionary of upstream routing connections. (keys=segments, values=adjacent upstream segments) upsegs : list List of segments ...
def handle(seq): """ Return only string surrounded by (). :param seq: (string) the string to process :return: (list of string) list of word in seq sourrounded by () """ seq = seq.replace("()", "") start = 0 res = [] word = "" for w in seq: if w == "(": start ...
def safe_div(dividend, divisor, divide_by_zero_value=0): """Return the result of division, allowing the divisor to be zero.""" return dividend / divisor if divisor != 0 else divide_by_zero_value
def create_surrogate_string(instr: str): """ Preserve newlines and replace all other characters with spaces :return whitespace string with same length as instr and with the same line breaks """ return ''.join(['\n' if e == '\n' else ' ' for e in instr])
def modinv(a, b): """Returns the modular inverse of a mod b. Pre: a < b and gcd(a, b) = 1 Adapted from https://en.wikibooks.org/wiki/Algorithm_Implementation/ Mathematics/Extended_Euclidean_algorithm#Python """ saved = b x, y, u, v = 0, 1, 1, 0 while a: q, r = b // a, b % a ...
def car_current(t): """ Piecewise constant current as a function of time in seconds. This is adapted from the file getCarCurrent.m, which is part of the LIONSIMBA toolbox [1]_. References ---------- .. [1] M Torchio, L Magni, R Bushan Gopaluni, RD Braatz, and D. Raimondoa. LIONSIMBA:...
def to_height(data: float, height: int, max_value: float, min_value: float) -> float: """translate the data to a height""" return (data - min_value) / (max_value - min_value) * height
def build_flags_string(flags): """Format a string of value-less flags. Pass in a dictionary mapping flags to booleans. Those flags set to true are included in the returned string. Usage: build_flags_string({ '--no-ttl': True, '--no-name': False, '--verbose':...
def is_monotonic(x, increasing=True): """ This function checks whether a given list is monotonically increasing (or decreasing). By definition, "monotonically increasing" means the same as "strictly non-decreasing". Adapted from: http://stackoverflow.com/questions/4983258/python-how-to-chec...
def check_template_sample(template_object, sample_set): """ check_template_sample checks if a template has a sample associated in the samples/ folder Args: template_object: the template dict to check, which got parsed from the file content sample_set: set of sample kinds (string) built by b...
def check_direction(direction_string, valid_directions): """check direction string :param direction_string - string :param valid_directions - string :return boolean""" if direction_string is None or len(direction_string) == 0: return False for direction in direction_string: if di...
def mars_exploration(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/mars-exploration/problem Sami's spaceship crashed on Mars! She sends a series of SOS messages to Earth for help. Letters in some of the SOS messages are altered by cosmic radiation during transmission. Given the signal r...
def populate_table_data(tenants): """Generates entries used to populate tenant table.""" result = [] for tenant in tenants: name = str(tenant.name) checkbox_html_template = '<input type="checkbox" id="{name}" name="{name}" {option} checked>' import_option = 'class="table_checkbox" on...
def check_pal(phrase): """ Checks whether a phrase is a palindrome or not. >>> check_pal('Reviled did I live, said I, as evil I did deliver') True """ import re p = re.compile('\W') phrase = p.sub('', phrase).lower() # With list # rev = list(phrase) # rev.reverse() # ...
def RemoveDuplicatedVertices(vertices, faces, vnorms=None): """Remove duplicated vertices and re-index the polygonal faces such that they share vertices""" vl = {} vrl = {} nvert = 0 vertList = [] normList = [] for i, v in enumerate(vertices): key = "%f%f%f" % tuple(v) i...
def to_cmd_param(variable: str) -> str: """ Convert a variable in a command parameter format """ return variable.replace('_', '-')
def compute_giou(arg_obj, ref_obj): """ Compute the generalized intersection over union code described in the paper available from: https://giou.stanford.edu/GIoU.pdf Page 4 of the paper has the psuedocode for this algorithm :param arg_obj: The argument object represented as a bounding box :param r...
def is_enz (node): """Tells if node is an enzyme (EC) or not""" split = node.split(".") if len(split) == 4 :#and np.all(np.array([sp.isdigit() for sp in split]) == True) : return True else: return False
def method_available(klass, method): """Checks if the provided class supports and can call the provided method.""" return callable(getattr(klass, method, None))
def number_greater_than(element, value, score): """Check if element is greater than config value. Args: element (float) : Usually vcf record value (float) : Config value score (integer) : config score Return: Float: Score """ if element > value: ret...
def create_node(n,*args): """ Parameters: ----------- n : int Node number *args: tuple, int, float *args must be a tuple of (x,y,z) coordinates or x, y and z coordinates as arguments. :: # Example node1 = 1 node2 = 2 create_n...
def str_to_dpid (s): """ Convert a DPID in the canonical string form into a long int. """ if s.lower().startswith("0x"): s = s[2:] s = s.replace("-", "").split("|", 2) a = int(s[0], 16) if a > 0xffFFffFFffFF: b = a >> 48 a &= 0xffFFffFFffFF else: b = 0 if len(s) == 2: b = int(s[1])...
def add_nested_field_to_es(nested_field, text, es_doc): """ Add a text to an appropriate field in a given elasticsearch-form document.""" if nested_field not in es_doc: # create a new es_doc[nested_field] = text else: # append to existed one es_doc[nested_field] = "|"...
def find_ask(asks, t_depth: float): """find best ask in the orderbook needed to fill an order of amount t_depth""" price = 0.0 depth = 0.0 for a in asks: price = float(a['price']) depth += float(a['amount']) if depth >= t_depth: break return round(price + 0.0...
def getObjectName(o): """ Return the name of an host object @type o: hostObject @param o: an host object @rtype: string @return: the name of the host object """ name="" return name
def wood_mono_to_string(mono, latex=False): """ String representation of element of Wood's Y and Z bases. This is used by the _repr_ and _latex_ methods. INPUT: - ``mono`` - tuple of pairs of non-negative integers (s,t) - ``latex`` - boolean (optional, default False), if true, output L...
def is_letter_guessed_correctly(player_input, secret_word): """ check whether the (guessed_letter/ player_input) is in the secret_word Arguments: player_input (string): the player_input secret_word (string): the secret, random word that the player should guess Returns: boolean: True if the player_in...
def get_leaf_branch_nodes(neighbors): """" Create list of candidates for leaf and branching nodes. Args: neighbors: dict of neighbors per node """ all_nodes = list(neighbors.keys()) leafs = [i for i in all_nodes if len(neighbors[i]) == 1] candidates = leafs next_nodes = [] ...
def set_metrics_facts_if_unset(facts): """ Set cluster metrics facts if not already present in facts dict dict: the facts dict updated with the generated cluster metrics facts if missing Args: facts (dict): existing facts Returns: dict: the facts dict ...
def edgesFromNode(n): """Return the two edges coorsponding to node n""" if n == 0: return 0, 2 if n == 1: return 0, 3 if n == 2: return 1, 2 if n == 3: return 1, 3
def transcribe(dna): """Return DNA string as RNA string.""" return dna.replace('T', 'U').replace('t','u')
def num_cycle_scenarios(k): """Compute the number (and the length) of scenarios for a cycle with the given size.""" if k % 2 == 1: print("ERROR: Odd cycle size.") exit(-1) l = (k // 2) - 1 s = (l + 1) ** (l - 1) return s, l
def application_instance_multiplier(value, app, dig_it_up, api_version=None): """Digs up the number of instances of the supplied app, and returns the value multiplied by the number of instances """ response = None instances = dig_it_up(app, 'instances') if instances is not None: response...
def matches(item, *, plugins=None, subregions=None): """ Checks whether the item matches zero or more constraints. ``plugins`` should be a tuple of plugin classes or ``None`` if the type shouldn't be checked. ``subregions`` should be set of allowed ``subregion`` attribute values or ``None`` if...
def _denominate(total): """ Coverts bucket size to human readable bytes. """ total = float(total) denomination = ["KB", "MB","GB","TB"] for x in denomination: if total > 1024: total = total / 1024 if total < 1024: total = round(total, 2) total ...
def analysis_nindex_usages(analysis): """ Returns a dictionary of namespace usages by name. 'nindex' stands for 'namespace index'. """ return analysis.get("nindex_usages", {})
def is_dictionary(obj): """Helper method for testing if the object is a dictionary. >>> is_dictionary({'key':'value'}) True """ return type(obj) is dict
def _intervalOverlap(a, b): """ Return overlap between two intervals Args: a (list or tuple): first interval b (list or tuple): second interval Returns: float: overlap between the intervals Example: >>> _intervalOverlap( [0,2], [0,1]) 1 """ return max(0, min(a[1...
def methods_hydrodynamic(): """ Returns a list containing the valid method keys that have used hydrodynamic simulations. """ hydro = [ "Batten2021", ] return hydro
def crosses(split1, split2): """ Check whether the splits intersect. """ intersect = False #print(split1, split2) #if bool(set(split1).intersection(split2)): if not (set(split1).isdisjoint(split2) or set(split1).issubset(split2) or set(split2).issubset(split1)): interse...
def get_unsupported_pytorch_ops(model_path): """ return unsupported layers in caffe prototxt A List. """ ret = list() return ret
def get_arxiv_id(result_record): """ :param result_record: :return: """ identifiers = result_record.get("identifier", []) for identifier in identifiers: if "arXiv:" in identifier: return identifier.replace("arXiv:", "") if "ascl:" in identifier: return id...
def _unique_item_counts(iterable): """ Build a dictionary giving the count of each unique item in a sequence. :param iterable: sequence to obtain counts for :type iterable: iterable object :rtype: dict[obj: int] """ items = tuple(iterable) return {item: items.count(item) for i...
def depth(d): """Check dictionary depth""" if isinstance(d, dict): return 1 + (max(map(depth, d.values())) if d else 0) return 0
def get_record_list(data, record_list_level): """ Dig the raw data to the level that contains the list of the records """ if not record_list_level: return data for x in record_list_level.split(","): data = data[x] return data
def gcd(a,b): """Returns the greatest common divisor of two numbers. """ if (b==0): return a else: return(gcd(b,a % b))
def is_command(text: str) -> bool: """Returns true if specified message is a command.""" return text.startswith("pp")
def fractional_part(numerator, denominator): """The fractional_part function divides the numerator by the denominator, and returns just the fractional part (a number between 0 and 1).""" if denominator != 0: return (numerator % denominator) / denominator return 0
def bitxor(a, b): """ Xor two bit strings (trims the longer input) """ return "".join([str(int(x) ^ int(y)) for (x, y) in zip(a, b)])
def construct_regex(parser_names): """ This regex is a modified version of wordpress origianl shortcode parser found here https://core.trac.wordpress.org/browser/trunk/src/wp-includes/shortcodes.php?rev=28413#L225 '\[' // Opening bracket '(\[?)' // 1: O...
def qiime_to_maaslin(in_datafile, outfile): """Converts a tsv file from qiime to a maaslin format :param in_datafile: String; file of the qiime tsv format (from biom_to_tsv) :param outfile: String; file of the tsv format for input to maaslin External dependencies - QiimeToMaaslin: https://b...
def discount(cost, parameters, capex): """ Discount costs based on asset_lifetime. """ # asset_lifetime = parameters['return_period'] # discount_rate = parameters['discount_rate'] / 100 # if capex == 1: # capex = cost # opex = round(capex * (parameters['opex_percentage_of_cape...
def _resolve_callable(c): """Helper to resolve a callable to its value, even if they are embedded. :param c: FN() -> value-or-callable :returns: fn(fn(fn....)) :raises: possibly anything, depending on the callable """ while callable(c): c = c() return c
def check_bool(text: str) -> bool: """Check if a string is bool-like and return that.""" text = text.lower() if text in ('true', 't', '1', 'yes', 'y', 'on'): return True else: return False
def flatten(nums): """flatten a list: [1,2,[3,4. [5],[6,7,[8,[9]]]]] """ result = [] for num in nums: print(result) if type(num) is list: for i in num: if type(i) is list: result.extend(i) else: result.ap...
def get_stack_name(job_identifier, obj): """Formats the stack name and make sure it meets LEO and CloudFormations naming requirements.""" stack_name = "{}-{}".format(job_identifier, obj) # Below checks if the stack_name meets all requirements. stack_name_parts = [] if not stack_name[0].isalpha(): ...
def region(lat, lon): """ Return the SRTM3 region name of a given lat, lon. Map of regions: http://dds.cr.usgs.gov/srtm/version2_1/Documentation/Continent_def.gif """ if -45 <= lat and lat < -25 and -180 <= lon and lon < -175: # southern hemisphere, near dateline return ...
def towards(a, b, amount): """amount between [0,1] -> [a,b]""" return (amount * (b - a)) + a
def is_parser(parser): """ Parsers are modules with a parse function dropped in the 'parsers' folder. When attempting to parse a file, QCRI will load and try all parsers, returning a list of the ones that worked. todo: load them from config """ return hasattr(parser, 'parse') and hasattr(par...
def get_pacer_case_id_from_docket_url(url): """Extract the pacer case ID from the docket URL. In: https://ecf.almd.uscourts.gov/cgi-bin/DktRpt.pl?56120 Out: 56120 In: https://ecf.azb.uscourts.gov/cgi-bin/iquery.pl?625371913403797-L_9999_1-0-663150 Out: 663150 """ param = url.split('?')[1] ...
def get_region(zone): """Converts us-central1-f into us-central1.""" return '-'.join(zone.split('-')[:2])
def gon2deg(ang): """ convert from gon to degrees Parameters ---------- ang : unit=gon, range=0...400 Returns ------- ang : unit=degrees, range=0...360 See Also -------- deg2gon, deg2compass """ ang *= 360/400 return ang
def children(tree): """ Given an ast tree get all children. For PHP, children are anything with a nodeType. :param tree_el ast: :rtype: list[ast] """ assert isinstance(tree, dict) ret = [] for v in tree.values(): if isinstance(v, list): for el in v: ...
def is_in_any_txt(txt, within_txts_list, case_insensitive=False): """is "txt" in any of the texts list ?""" for within_txt in within_txts_list: if case_insensitive: # slower if txt.lower() in within_txt.lower(): return True else: if txt in...
def setBillNumberQuery(billnumber: str) -> dict: """ Sets Elasticsearch query by bill number Args: billnumber (str): billnumber (no version) Returns: dict: [description] "hits" : [ { "_index" : "billsections", "_type" : "_doc", "_id" : "yH0adHcByMv3L6kFH...
def fahrenheit(value): """ Convert Celsius to Fahrenheit """ return round((value * 9 / 5) + 32, 1)
def generate_occluder_pole_position_x( wall_x_position: float, wall_x_scale: float, sideways_left: bool ) -> float: """Generate and return the X position for a sideways occluder's pole object using the given properties.""" if sideways_left: return -3 + wall_x_position - wall_x_scale / 2 ...
def validate_boolean(value, label): """Validates that the given value is a boolean.""" if not isinstance(value, bool): raise ValueError('Invalid type for {0}: {1}.'.format(label, value)) return value
def load_text_file(filename): """ Returns a list of sequences separated by carriage returns in the file. Words are strings of characters. Whitespace is stripped. Capital letters removed. """ in_file = open(filename, 'r') wordlist = [] for line in in_file: wordlist.append(line.strip()...
def in_range(low, high, max): """ Determines if the passed values are in the range. """ if (low < 0 or low > high): return 0 if (high < 0 or high > max): return 0 return 1
def is_anagram(str1: str, str2: str) -> bool: """Check if the given two strings are anagrams Worst: O(nlog n) Best: O(n) """ str1_list = sorted(str1) str2_list = sorted(str2) return str1_list == str2_list
def validate_comma_separated_list(setting, value, option_parser, config_parser=None, config_section=None): """Check/normalize list arguments (split at "," and strip whitespace). """ # `value` is already a ``list`` when given as command line option # and "action"...
def filter_object_parameters(ob, list_of_parameters): """Return an object of just the list of paramters.""" new_ob = {} for par in list_of_parameters: try: new_ob[par] = ob[par] except KeyError: new_ob[par] = None return new_ob
def is_leap(year: int) -> bool: """ https://stackoverflow.com/a/30714165 """ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def has_navigation(node, key=None): """Returns ``True`` if the node has a :class:`.Navigation` with the given key and ``False`` otherwise. If ``key`` is ``None``, returns whether the node has any :class:`.Navigation`\ s at all.""" try: return bool(node.navigation[key]) except: return False
def get_html(html: str): """Convert HTML so it can be rendered.""" WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>""" # Newlines seem to mess with the rendering html = html.replace("\n", " ") return WRAPPER....
def default(v, d): """Returns d when v is empty (string, list, etc) or false""" if not v: v = d return v
def iobes_iob(tags): """ IOBES -> IOB """ new_tags = [] for i, tag in enumerate(tags): if tag.split('-')[0] == 'B': new_tags.append(tag) elif tag.split('-')[0] == 'I': new_tags.append(tag) elif tag.split('-')[0] == 'S': new_tags.append(tag....
def to_lower(string): """The lower case version of a string""" return string.lower()
def fail_rate(num_fail, num_pass): """Computes fails rate, return N/A if total is 0.""" total = num_fail + num_pass if total: return "{:.3f}".format(round(num_fail / total, 3)) return "N/A"
def _convert_scale(target_value, max_value): """If target_value is float, mult with max_value otherwise take it straight""" if target_value <= 1: return int(max_value * target_value) assert target_value <= max_value return target_value
def make_readable(seconds): """ seconds: number of seconds to translate into hours, minutes and second return: seconds into hours, minutes and seconds in a digital clock format """ second = 0 minute = 0 hour = 0 if seconds <= 359999: for i in range(seconds): second += 1 if second >= ...
def rotate_voxel(xmin, ymin, xmax, ymax): """ Given center position, rotate to the first quadrant Parameters ---------- xmin: float low point X position, mm ymin: float low point Y position, mm xmax: float high point X position, mm ymax: float ...
def residcomp(z1, z0, linelength=1): """ Residual Compensation Factor Function. Evaluates the residual compensation factor based on the line's positive and zero sequence impedance characteristics. Parameters ---------- z1: complex The positive-sequence impedance ...
def dumb_fibonacci(i, seq=None): """Dumb solution""" if i <= 1: return 1, 0, [0] if i == 2: return 2, 1, [0, 1] result1 = dumb_fibonacci(i - 1) result2 = dumb_fibonacci(i - 2) seq = result1[2] seq.append(result1[1] + result2[1]) return i, seq[i - 1], seq[:i]
def label2tag(label_sequence, tag_vocab): """ convert label sequence to tag sequence :param label_sequence: label sequence :param tag_vocab: tag vocabulary, i.e., mapping between tag and label :return: """ inv_tag_vocab = {} for tag in tag_vocab: label = tag_vocab[tag] in...