content
stringlengths
42
6.51k
def _canonicalize_axis(axis, num_dims): """Canonicalize an axis in (-num_dims, num_dims) to [0, num_dims).""" axis = int(axis) if axis < 0: axis = axis + num_dims if axis < 0 or axis >= num_dims: raise ValueError( "axis {} is out of bounds for array of dimension {}".format( axi...
def add_two_numbers(first_number, second_number): """ Params: first_number(int/float): The first number to add second_number(int/float): The second number to add Returns: result(int/float): The added result of two numbers """ result = first_number + second_number return ...
def get_spells(monster_data): """Returns a string list of spells the monster can cast.""" spells = [] for ability in monster_data.get("special_abilities", []): if ability['name'] == "Spellcasting": spells = ['"%s"' % spell["name"].lower() for spell in ability["spellcasting"]["spells"]] ...
def _pack_uint32(x): """Convert a 32-bit integer to little-endian.""" return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little')
def pad_list(l, pad_token, max_l_size, keep_lasts=False, pad_right=True): """ Adds a padding token to a list inputs: :param l: input list to pad. :param pad_token: value to add as padding. :param max_l_size: length of the new padded list to return, it truncates lists longer that 'max_l_size'...
def majority(samples, ignore_none=True): """ Find the most frequent element in a list. Arguments: samples (list): Input list. Its elements must be hashable. ignore_none (bool): If None is a valid value. Returns: object: The most frequent element in samples. Returns none if the ...
def is_unified(target): """ PTX has two modes of operation. In the unified mode, texture and sampler information is accessed through a single .texref handle. In the independent mode, texture and sampler information each have their own handle, allowing them to be defined separately and combined at the site o...
def find_cell_with_tags(nb, tags): """ Find the first cell with any of the given tags, returns a dictionary with 'cell' (cell object) and 'index', the cell index. """ tags_to_find = list(tags) tags_found = {} for index, cell in enumerate(nb['cells']): for tag in cell['metadata'].get...
def mapped_actors(data): """ Creates a mapping of actors to whom they have acted with. Returns a dictionary of form {actor_id_1: {actor_id_2}} """ d = {} # Map actor_1 to actor_2 and actor_2 to actor_1 for i in data: if i[0] not in d: d[i[0]] = set() ...
def common_letters(str1, str2): """Return common letters between two strings.""" dict_ = [] if len(str1) > len(str2): str_ = str1 else: str_ = str2 for letter in str_: if letter in str2 and letter in str1 and letter not in dict_: dict_.append(letter) return di...
def reverse(n: int) -> int: """ This function takes in input 'n' and returns 'n' with all digits reversed. Assume positive 'n'. """ reversed_n = [] while n != 0: i = n % 10 reversed_n.append(i) n = (n - i) // 10 return int(''.join(map(str, reversed_n)))
def change_keys(obj, convert): """ Recursively goes through the dictionary obj and replaces keys with the convert function Useful for fixing incorrect property keys, e.g. in JSON-LD dictionaries Credit: StackOverflow user 'baldr' (https://web.archive.org/web/20201022163147/https://stackoverflow.co...
def set_ibit(num: int, index: int, value: int, length: int = 1) -> int: """Replaces a slice of a binary integer with another integer. Parameters ---------- num : int The binary integer. index : int The index of the slice (start). value : int The binary value to insert in...
def greet(name): """ function greet() inside dec5 sample """ print(f"Hello {name}") return 42
def load_federated_extensions(federated_extensions: dict) -> list: """Load the list of extensions""" extensions = [] for name, data in federated_extensions.items(): build_info = data["quetz"]["_build"] build_info["name"] = name extensions.append(build_info) return extensions
def __intval(x, default=0): """ convert str to int value. Returns: int """ if not x or not str(x).isdigit(): return default return int(x)
def samps2ms(samples: float, sr: int) -> float: """samples to milliseconds given a sampling rate""" return (samples / sr) * 1000.0
def remove_whitespace(original: str) -> str: """ >>> remove_whitespace("I Love Python") 'ILovePython' >>> remove_whitespace("I Love Python") 'ILovePython' >>> remove_whitespace(' I Love Python') 'ILovePython' >>> remove_whitespace("") '' """ return "".join...
def str_eval(s: str) -> int: """ Returns product of digits in given string n >>> str_eval("987654321") 362880 >>> str_eval("22222222") 256 """ product = 1 for digit in s: product *= int(digit) return product
def little_endian_to_int(b): """little_endian_to_int takes byte sequence as a little-endian number. Returns an integer""" # use the int.from_bytes(b, <endianness>) method return int.from_bytes(b, "little")
def get_sense(word): """Function that gets the sense of a certain word in aligned AMR""" if '~' in word: sense = word.split('~')[-1].split('.')[-1] # extract 16 in e.g. house~e.16 if ',' in sense: # some amr-words refer to multiple tokens. If that's the case, we take the average for calculat...
def radix_sort(s): """Perform a radix sort on sequence. :param s: iterable sequence :return: new list of items from s in sorted order """ if len(s) == 0: return s digit = 0 max = s[0] max_digits = len(str(max)) # Keep repeating until digit == the # of digits in the max value...
def bubble_sort(nsl: list) -> list: """ classic sorting algorithm - bubble sort. :param nsl: type list: non sorted list :return: type list: sorted list """ sl = nsl[:] n = len(sl) if n < 2: return sl for i in range(len(sl)): for j in range(len(sl) - 1, i, -1): ...
def clean_name(name: str) -> str: """ Changes a word/few words to lower case and separated by _ instead of spaces. Args: name (str): Returns: str: """ return '_'.join(name.split(' ')).lower()
def transform_references(old_references): """ Covert old reference format to new reference format """ new_references = [] for ref in old_references: new_ref = {} new_ref['verification_key'] = ref['verification'] component_key = ref.get('component') system_key = ref.get('syste...
def field_check(field1, field2) -> None: """ For testing """ test1 = field1 test2 = field2 file = open('field_check.txt', 'w+') file.writelines(test1) file.writelines('\n') file.writelines(test2) file.close() return None
def get_TD_error(new_value, value, reward, has_finished, discount): """Return TD error. Args: new_value: Value at next state. value: Value at current state. reward: Reward in transitioning to next state. has_finished: If the game has finished. discount: Discount factor. ...
def slice_text(text, eos_token="SEQUENCE_END", sos_token="SEQUENCE_START"): """Slices text from SEQUENCE_START to SEQUENCE_END, not including these special tokens. """ eos_index = text.find(eos_token) text = text[:eos_index] if eos_index > -1 else text sos_index = text.find(sos...
def resample_pick(data, step): """Resample by picking every `step`th value.""" return data[::step]
def ws_message_subscribed_fixture(ws_message_subscribed_data): """Define a fixture to represent the "registered" response.""" return { "data": ws_message_subscribed_data, "datacontenttype": "application/json", "id": "id:16803409109", "source": "service", "specversion": "1...
def join_css_classes_list(css_classes_list): """ Join the provided list of css classes into a string. """ return ' '.join(css_classes_list)
def make_groupby(period, groupby): """Make GROUP BY part of the InfluxDB query. :param period - time in second for the grouping by. :param groupby - list of fields for group by :return str like `field1, field2, time(10s)` """ if groupby: groupby = [field.replace("resource_metadata", "m...
def has_zero_dependents(nodes): """Check whether there are any nodes which do notdepend on anything""" number = len([node for node in nodes if len(node.dependents) == 0]) return number > 0
def resolve(path): """ Resolve a realtive path or shot tree URI to a full path. :rtype: str :return: the full path """ path = str(path) return path
def _attrs_equal(lhs, rhs): """ Helper function to compare two strings or two QueryableAttributes. QueryableAttributes can't be compared with `==` to confirm both are same object. But strings can't be compared with `is` to confirm they are the same string. We have to change the operator based on typ...
def get_4d_idx(day): """ A small utility function for indexing into a 4D dataset represented as a 3D dataset. [month, level, y, x], where level contains 37 levels, and day contains 28, 29, 30 or 31 days. """ start = 1 + 37 * (day - 1) stop = start + 37 return list(range(start, stop, ...
def check_inside_area(index, index_list): """ Check Inside, return True if inside """ if index in index_list: return True return False
def utcstr(ts): """ Format UTC timestamp in ISO 8601 format. :param ts: The timestamp to format. :type ts: instance of :py:class:`datetime.datetime` :returns: Timestamp formatted in ISO 8601 format. :rtype: unicode """ if ts: return ts.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z...
def starcheck_link(obsid): """ Construct/return a link to the starcheck printer CGI. Making these kind of links scales well, as there are no database lookup required for each obsid until the link is clicked. """ icxc_cgi_bin = "https://icxc.harvard.edu/cgi-bin/aspect/" starcheck_html = "{top...
def prune_graph(adj_lists, relations): """The function is used to prune graph based on the relations that are present in the training Arguments: adj_lists {dict} -- dictionary containing the graph relations {set} -- list of relation ids Returns: dict -- pruned graph """ ...
def intensity2depth(intensity, interval=300): """ Function for convertion rainfall intensity (mm/h) to rainfall depth (in mm) Args: intensity: float float or array of float rainfall intensity (mm/h) interval : number time interval (in sec) which is correspondend...
def point_to_polygon_geojson(g): """ Takes a GeoJSON point and converts it into a GeoJSON polygon GeoJSON polygons must have 0 or >= 4 points so the GeoJSON point coordinates are duplicated 4 times """ point_coordinates = g['geometry']['coordinates'] polygon_geojson = { 'type': '...
def cir_RsQ_fit(params, w): """ Fit Function: -Rs-Q- """ Rs = params["Rs"] Q = params["Q"] n = params["n"] return Rs + 1 / (Q * (w * 1j) ** n)
def TrimSequence(sequence, front_cutoff, end_cutoff): """ This function takes a sequence and trims the ends off by the specified cutoffs. Parameters: - front_cutoff: the number of positions to trim off at the front - end_cutoff: the number of positions to trim off at the end - sequence: the sequence to be trimm...
def has_lower(s: str) -> bool: """ Returns True if the string consists of one or more lower case characters, True otherwise. """ if isinstance(s, str): return len(s) > 0 and not s.isupper() raise TypeError("invalid input - not a string")
def hello_name(name: str): """Return a string greeting the name.""" return f"Hello {name}!"
def create_table(title: str, data: dict, headers: str, **kwargs): """ Creates table given object and headers Usage: `{% create_table 'carparks' carpark 'name|description' %}` """ return {'title': title, 'headers': headers.split("|"), 'data': data, **kwargs}
def add_output_file(args, output_file): """Append an output file to args, presuming not already specified.""" return args + ['-o', output_file]
def get_media(dictionary, key, lst): """ This function requires a list of synonyms for a specific medium. It will construct a dictionary that maps the key to various synonyms of the medium. """ for i in lst: try: dictionary[key].append(i) except KeyError: ...
def merge_dict(base, delta): """ Recursively merging dictionaries. Args: base: Target for merge delta: Dictionary to merge into base """ for k, dv in delta.items(): bv = base.get(k) if isinstance(dv, dict) and isinstance(bv, dict): merge...
def div_list(ls,n): """ """ if not isinstance(ls,list) or not isinstance(n,int): return [] ls_len = len(ls) if n<=0 or ls_len==0: return [] if n>ls_len: return [] elif n == ls_len: return [[i] for i in ls] else: j = (int)(ls_len/n) k = ls_len%n ls_return = [] for i in range(0...
def hilite(string, ok=True, bold=False): """Return an highlighted version of 'string'.""" attr = [] if ok is None: # no color pass elif ok: # green attr.append('32') else: # red attr.append('31') if bold: attr.append('1') return '\x1b[%sm%s\x1b[0m' % (';'...
def strip_non_alpa(text): """ Strip string from non alpha caracters """ letters = [] for let in list(text): if let.isalpha(): letters.append(let) return letters
def pointCheck(point, interval): """ Returns True if point is within interval Arguments: point = integer interval = chromosome/assemby, start, stop with start and stop being integers """ assert isinstance(point, int) assert isinstance(interval[1], int) assert isinstance(interval[2], int...
def decimal_isolate(number, digitAmount): """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. >>> decimal_isolate(1.53, 0) 0.53 >>> decimal_isolate(35.345, 1) 0.3 >>> decimal_isolate(35.345, 2) 0.34 ...
def _format_node(e): """ Internal function to format a node element into a dictionary. """ ignored_tags = [ "source", "source_ref", "source:ref", "history", "attribution", "created_by", "tiger:tlid", "tiger:upload_uuid", ] node = ...
def share_diagonal(x0, y0, x1, y1): """ Is (x0, y0) on a shared diagonal with (x1, y1)? """ dy = abs(y1 - y0) # Calc the absolute y distance dx = abs(x1 - x0) # CXalc the absolute x distance return dx == dy # They clash if dx == dy
def maybe_list(value): """maybe list """ if hasattr(value, "__iter__"): return value if value is None: return [] return [value]
def get_bit(byte, bit_num): """ Return bit number bit_num from right in byte. @param int byte: a given byte @param int bit_num: a specific bit number within the byte @rtype: int >>> get_bit(0b00000101, 2) 1 >>> get_bit(0b00000101, 1) 0 """ return (byte & (1 << bit_n...
def find_2d_bin(i,j,n_class): """ i is the first velocity class for v_n, j is the velocity class for v_n+1 n_class is the number of classes for the order one Markov chain the function returns the class for the pair (v_n, v_n+1) """ assert(i<n_class and j<n_class) return (i)*n_class + j
def patch_numbers_from_log(msg): """ Weak method to pull patch numbers out of a commit log. rely on the fact that its unlikely any given number will match up with a closed patch but its possible. """ patches = [] msg = msg.replace(",", " ") msg = msg.replace(".", " ") msg = msg.r...
def _feature_tokenize( string, layer=0, tok_delim=None, feat_delim=None, truncate=None, lower=False): """Split apart word features (like POS/NER tags) from the tokens. Args: string (str): A string with ``tok_delim`` joining tokens and features joined by ``feat_delim``. For example, ...
def human_list(_list) -> str: """Convert a list of items into 'a, b or c'""" last_item = _list.pop() result = ", ".join(_list) return "%s or %s" % (result, last_item)
def tsRange(ts, value): """Converts timestamp to range[ts - value TO ts + value] with value in millis.""" if not value or not ts: return "" time = int(ts) val = int(value) return "[%d TO %d]" % (time - val, time + val)
def generate_baseline(_iterable, window_length): """ Generate a sliding baseline of an iterable Creates a list of sliding baselines for the iterable. e.g. if you pass in a list of len==5 with a baseline length of 2, we will generate: [ [elem0 (first element), elem1, elem2], [elem1, elem2, e...
def is_supplementary_code_point(body: str, location: int) -> bool: """ Check whether the current location is a supplementary code point. The GraphQL specification defines source text as a sequence of unicode scalar values (which Unicode defines to exclude surrogate code points). """ try: ...
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.strip()] return data
def _bool_to_json(value): """Coerce 'value' to an JSON-compatible representation.""" if isinstance(value, bool): value = "true" if value else "false" return value
def add_add_to_args(args): """Helper function that puts the add subcommand add in front for dev convience""" return [["add"] + arg for arg in args]
def calc_numsteps(low, high, step, endpoint=True): """Calculate the number of 'step' steps between 'low' and 'high'""" num_steps = (high - low) // step if endpoint: num_steps += 1 return int(num_steps)
def hamming_distance(s1, s2) -> int: """Return the Hamming distance between equal-length sequences.""" if len(s1) != len(s2): raise ValueError('Unequal lengths of input objects') return sum((x != y) for x, y in zip(s1, s2))
def set2key(s): """ change a set to string key """ return ' '.join(str(x) for x in s)
def cleanup(form_data): """Helper Function to strip out empty field values""" return {key:val for key,val in form_data.items() if val}
def scale_daily_temp(mean_temp, daily_temp, scale_params): """linear scale daily temp""" scaled_daily_temp = (daily_temp - mean_temp)/\ (scale_params[0] - scale_params[1]*mean_temp) return scaled_daily_temp
def setMazecontent(maze, positions, itemValue): """ Sets Stars or Energy by adding the value to the field if the field is empty (0) filed gets item placed either 2 or 4 if the item has a wall field gets item placed but keeps walls values is set to 3 or 5 @param maze: 2D maze array @param positio...
def _mkx(i, steps, n): """ Generate list according to pattern of g0 and b0. """ x = [] for step in steps: x.extend(range(i, step + n, n)) i = step + (n - 1) return x
def _group_to_str(group: list): """ Format a group of parameter name suffixes into a loggable string. Args: group (list[str]): list of parameter name suffixes. Returns: str: formated string. """ if len(group) == 0: return "" if len(group) == 1: return "." + g...
def cidr_to_netmask(cidr): """Creates a decimal format of a CIDR value. **IPv4** only. For IPv6, please use `cidr_to_netmaskv6`. Args: cidr (int): A CIDR value. Returns: netmask (str): Decimal format representation of CIDR value. Example: >>> from netutils.ip import cidr_t...
def normalize_word(s: str) -> str: """Normalize a word. Args: s: A word. Returns: The word in lower case. """ return s.lower()
def f1_at_n(is_match, potential_matches, n): """ Takes a boolean list denoting if the n-th entry of the predictions is an actual match and the number of potential matches, i.e. how many matches are at most possible and an integer n and computed the f1 score if one were to only consider the n most re...
def check_parse_type(raw): """ Checks the type for which the given value should be parsed. Currently only detects strings and arrays.""" if raw.strip()[0] == '[': return 'array' else: return 'string'
def compile_query(server, queries=None, response_types=None, subtrees=None): """ Queries are string queries, e.g., "COVID-19" Response types are e.g., "dataverse", "dataset", "file" Subtrees are specific dataverse IDs All can have multiple values. Response types and subtrees are OR'd Queries ar...
def number_of_days_in_period(periodType, timeToElapse): """ Receives the period type and calculates the number of days in that period """ if periodType == "days": return timeToElapse elif periodType == "weeks": return timeToElapse * 7 elif periodType == "months": return timeToEl...
def df(x,kwargs): """Modify x using keyword arguments (dicts,kwarg).""" return x if x not in kwargs else kwargs[x]
def constraint_query(node_var, node_label, node_property): """Generate query for creating a constraint on a property.""" query = "CONSTRAINT ON ({}:{}) ASSERT {}.{} IS UNIQUE".format( node_var, node_label, node_var, node_property ) return query
def cast_ext(ext: str) -> str: """Convert ext to a unified form.""" ext = ext.lower() if ext == 'jpeg': ext = 'jpg' return ext
def TopologicalSort(changes): """Sort changes in topological order. Args: changes: a dictionary, which maps commit hashes to commit objects:: { '<commit hash>': { 'subject': '<subject>', 'change_id': '<gerrit change ID>', 'parent': '<parent commit hash>', ...
def tuple_add(t1, t2): """ Add two tupples, elementwise. """ return tuple(map(sum, zip(t1, t2)))
def triangle_area(base, height): """Returns the area of a triangle""" # You have to code here # REMEMBER: Tests first!!! return (base * height)/2
def prep_addr(addr, iface, prot=u'ipv4'): """Ensure specific structure for IP address dict.""" if iface not in addr: addr[iface] = {} if prot not in addr[iface]: addr[iface][prot] = {} return addr
def get_connected_components(edges): """Compute the connected components given the EM pair predictions. Args: edges (list of tuples): the entity pairs of the form (left, right, lable) Returns: List of tuples: a list of (node, cluster_id) """ parent = {} def get_parent(node): ...
def mydict(*args, **kwargs): """Emulate Python 2.3 dict keyword support """ if args: raise NotImplementedError('args not supported') if kwargs: return kwargs else: return {}
def xgcd(a,b): """xgcd(a,b) returns a list of form [g,x,y], where g is gcd(a,b) and x,y satisfy the equation g = ax + by.""" a1=1; b1=0; a2=0; b2=1; aneg=1; bneg=1; swap = False if(a < 0): a = -a; aneg=-1 if(b < 0): b = -b; bneg=-1 if(b > a): swap = True [a,b] = [b,a] while (1): quot = -(a / b) a = a...
def get_percentage(new_price, old_price): """ Returns the percentage increase/decrease of the new price new_price based on the old price old_price. """ diff = new_price - old_price return (diff / old_price) * 100
def get_create_tables_queries(graph_name, backend): """Format a PostgreSQL CREATE TABLE query with the name of the RDF graph to insert.""" if backend == "postgres": return [( f"CREATE TABLE {graph_name} (" f"subject TEXT, " f"predicate TEXT, " f"object TEX...
def parse_request(event): """ Parses the input api gateway event and returns the product id Expects the input event to contain the pathPatameters dict with the user id and school id key/value pair :param event: api gateway event :return: a dict containing the user id and org id """ ...
def build_url(chapter, page): """ """ return 'http://www.japscan.com/lecture-en-ligne/love-hina/volume-%s/%s.html' % (chapter, page)
def parse_data_resources(resource_map=None): """ Returns a list of data resources found in a PASTA resource map """ data_resources = [] if resource_map: resources = resource_map.split('\n') for resource in resources: if '/data/' in resource: data_resources...
def getTimeFormat(seconds): """ format secends to h-m-s input:int output:int """ seconds = int(seconds) if seconds == 0: return 0 # Converts the seconds to standard time hour = seconds / 3600 minute = (seconds - hour * 3600) / 60 s = seconds % 60 resultstr = "" ...
def _estimate_fgbio_defaults(avg_coverage): """Provide fgbio defaults based on input sequence depth and coverage. For higher depth/duplication we want to use `--min-reads` to allow consensus calling in the duplicates: https://fulcrumgenomics.github.io/fgbio/tools/latest/CallMolecularConsensusReads.htm...