content
stringlengths
42
6.51k
def range_sum(lower, upper): """Find the sum of a range of numbers """ # sum(range(lower, upper + 1)) total = (upper + lower) * (upper - lower + 1) / 2 return total
def convert_base_list(lst, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): """Converts a "base-list" (something like what ```from_decimal``` would output) to a number (in string form).""" res = '' for i in lst: res += alphabet[i] return res
def _expand_global_features(B, T, g, bct=True): """Expand global conditioning features to all time steps Args: B (int): Batch size. T (int): Time length. g (Tensor): Global features, (B x C) or (B x C x 1). bct (bool) : returns (B x C x T) if True, otherwise (B x T x C) Ret...
def put_number(line_number, line): """ Return a string. The `line_number` is formatted as 3 digits number with a dot and a space preceding the `line`. The empty space before line number will be replaced by '0's. Example: >>> put_number(1, "Hello World!") '001. Hello World' """ retur...
def transcribe(seq: str) -> str: """ transcribes DNA to RNA by generating the complement sequence with T -> U replacement """ dic = {'A':'U', 'T':'A', 'C':'G', 'G':'C'} out = '' for char in seq: out += dic[char] return out
def clean_completion_name(name: str, char_before_cursor: str) -> str: """Clean the completion name, stripping bad surroundings. Currently, removes surrounding " and '. """ if char_before_cursor in {"'", '"'}: return name.lstrip(char_before_cursor) return name
def lists_from_options(poss, size, repetitions=True): """Returns a list of all possible lists of size ```size``` that consist only of items from ```poss```, a set.""" if not size: return [[]] res = [] prev = lists_from_options(poss, size-1) for lst in prev: if repetitions: ...
def Mean(values): """Returns the arithmetic mean, or NaN if the input is empty.""" if not values: return float('nan') return sum(values) / float(len(values))
def filter_by_dislikes(client_list: list, dislikes: list) -> list: """Receives a list of clients and returns a list of clients that have the specified dislikes D. Args: client_list (list): List of clients that has the form [[L,D,N]*]. dislikes (list): A list of dislikes in the form of a sorted ...
def CompareLists(gyp, gn, name, dont_care=None): """Return a report of any differences between two lists, ignoring anything in |dont_care|.""" if not dont_care: dont_care = [] output = '' if gyp[name] != gn[name]: output += ' %s differ:\n' % name gyp_set = set(gyp[name]) - set(dont_care) gn_s...
def precision_and_recall_at_k(ground_truth, prediction, k=-1): """ :param ground_truth: :param prediction: :param k: how far down the ranked list we look, set to -1 (default) for all of the predictions :return: """ if k == -1: k = len(prediction) prediction = prediction[0:k] ...
def find_all_indexes(text, pattern): """Return a list of starting indexes of all occurrences of pattern in text, or an empty list if not found. o(n) runtime, based off the length of the text.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'p...
def cantor(a, b): """Cantor pairing function, used to give unique int name to each observation""" a = int(a) b = int(b) return (a + b) * (a + b + 1) / 2 + b
def read_paralogs(paralogs_file): """Read list of paralogs.""" if paralogs_file is None: # then nothing to return return set() f = open(paralogs_file, "r") paralogs = set(x.rstrip() for x in f.readlines()) f.close() return paralogs
def get_name(mode): """ Returns name of given observation mode """ names = {} names['ANT'] = "Alpha-numeric Text" names['GWW3F'] = "Global Wave Model" names['RWW3A'] = "Regional Wave Analysis" names['SICEA'] = "Sea Ice" names['SSTA'] = "Sea Surface Temperature Analysis" names['S...
def check_iterable_1_not_smaller(iterable_1, iterable_2): """Checks two iterables of the same length for whether each element in 1 is at least as big as the corresponding element of 2 Inputs: iterable_1 - an iterable of arbitary length n iterable_2 - an iterable of length n which...
def validate_default_value(handler, default, norm, param="value"): """ assert helper that quickly validates default value. designed to get out of the way and reduce overhead when asserts are stripped. """ assert default is not None, "%s lacks default %s" % (handler.name, param) assert norm(defau...
def RGB(nRed, nGreen, nBlue): """Return an integer which repsents a color. The color is specified in RGB notation. Each of nRed, nGreen and nBlue must be a number from 0 to 255. """ return (int( nRed ) & 255) << 16 | (int( nGreen ) & 255) << 8 | (int( nBlue ) & 255)
def say_gday(name, age): """ Gday! """ # your code here return "Gday. My name is Alex and I'm 32 years old"
def conv_packed_binary_string_to_1_0_string(s): """ '\xAF' --> '10101111' """ r = [] for ch in s: x = ord(ch) for i in range(7,-1,-1): t = (x >> i) & 0x1 r.append(t) return ''.join(map(lambda x: chr(x + ord('0')), r))
def decode_string(data): """ Decode string and strip NULL-bytes from end.""" return data.decode('utf-8').rstrip('\0')
def g_iter(n): """Return the value of G(n), computed iteratively. >>> g_iter(1) 1 >>> g_iter(2) 2 >>> g_iter(3) 3 >>> g_iter(4) 10 >>> g_iter(5) 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion']) True """ "*** YOUR...
def get_window_args(wid): """wmctrl arguments that choose `wid` for further processing. """ return ["wmctrl","-i","-r",wid]
def MergeIndexRanges(section_list): """Given a list of (begin, end) ranges, return the merged ranges. Args: range_list: a list of index ranges as (begin, end) Return: a list of merged index ranges. """ actions = [] for section in section_list: if section[0] >= section[1]: raise Va...
def swap_32b(val): """ Swap 32b val :param val: 32b value :return: swapped 32b """ tmp = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF) tmp = (tmp << 16) | (tmp >> 16) return tmp & 0xFFFFFFFF
def tolerance(condition, sampling_rate=0): """Absolute tolerance for different condition.""" tol = 0 if condition == 8: tol = 2 ** -7 elif condition == 16: tol = 2 ** -11 # half precision elif condition == 24: tol = 2 ** -17 # to be checked elif condition == 32: ...
def state(row, i): """This function takes in the current row and the index of the item, and returns its state as and 0 =< integer =< 7 """ length = len(row) return row[i - 1] * 4 + row[i] * 2 + row[(i + 1) % length]
def rgb_to_int(red, green, blue): """ Given RGB components of a color, covnert this to an integer which is in the range of 0 (#000000) to 16777215 (#FFFFFF) >>> rgb_to_int(0, 0, 0) 0 >>> rgb_to_int(255, 0, 0) 16711680 >>> rgb_to_int(0, 255, 0) 65280 >>> rgb_to_int(0, 0, 255) ...
def reject_filter(record): """ A filter function to reject records. """ return record if record["int"] != 789 else None
def get_first(d, key): """Return value for d[key][0] if d[key] is a list with elements, else return d[key]. Useful to retrieve values from solr index (e.g. `title` and `text` fields), which are stored as lists. """ v = d.get(key) if isinstance(v, list): return v[0] if len(v) > 0 else No...
def list_hasnext(xs): """Whether the list is empty or not.""" return len(xs) > 0
def indexToCoordinate(index): """Return a board coordinate (e.g. e4) from index (e.g. [4, 4])""" return ("a", "b", "c", "d", "e", "f", "g", "h")[index[1]] + str(abs(index[0] - 8))
def check_kwargs(kwargs, default_kw): """ Check user-provided kwargs against defaults, and if some defaults aren't provided by user make sure they are provided to the function regardless. """ for key in default_kw: if key not in kwargs: kwargs[key] = default_kw[key] return kw...
def calc_rns(rs, albedo): """ Total incoming shortwave radiation. Parameters ---------- rs : numpy ndarray Total incoming shortwave solar radiation, in MegaJoules per square meter per day albedo : numpy ndarray Shortwave blue-sky albedo, unitless """ return (1. - albedo...
def fmt_time(ts, msp=False): """Converts nanosecond timestamps to timecodes. msp = Set timecodes for millisecond precision if True """ s = ts / 10 ** 9 m = s // 60 s = s % 60 h = m // 60 m = m % 60 if msp: return '{:02.0f}:{:02.0f}:{:06.3f}'.format(h, m, s) else...
def box(points): """Obtain a tight fitting axis-aligned box around point set""" xmin = min(points, key=lambda x: x[0])[0] ymin = min(points, key=lambda x: x[1])[1] xmax = max(points, key=lambda x: x[0])[0] ymax = max(points, key=lambda x: x[1])[1] return (xmin, ymin), (xmax, ymax)
def max_luck_balance(contests, num_can_lose): """ Returns a single integer denoting the maximum amount of luck Lena can have after all the contests. """ balance = 0 # We can lose all unimportant contests. unimportant_contests = [contest for contest in contests if contest[1] == 0] for co...
def urljoin(*args): """A custom version of urljoin that simply joins strings into a path. The real urljoin takes into account web semantics like when joining a url like /path this should be joined to http://host/path as it is an anchored link. We generally won't care about that in client. """ r...
def realord(s, pos=0): """ Returns the unicode of a character in a unicode string, taking surrogate pairs into account """ if s is None: return None code = ord(s[pos]) if code >= 0xD800 and code < 0xDC00: if len(s) <= pos + 1: print("realord warning: missing surro...
def set_dict_indices(my_array): """ Creates a dictionary based on values in my_array, and links each of them to an indice. :param my_array: An array (e.g. [a,b,c]) :return: A dictionary (e.g. {a:0, b:1, c:2}) """ my_dict = {} i = 0 for value in my_array: my_dict[value] = i ...
def compute_avg_wmd_distance(contexts1, contexts2, gensim_obj): """ Compute an average word metric distance :param contexts1: List of ContextAndEntities objects extracted from Document 1 :param contexts2: List of ContextAndEntities objects extracted from Document 2 :param gensim_obj: a Gensim object...
def greeting(greeting, name): """ Returns a greeting to a person. Args: greeting (str): A greeting. name (str): A person's name. Returns (str): A greeting to a person. """ # NOTES: # 1. String technique #3: %-interpolation # 2. Built-in function...
def to_int(num): """Convert decimal to integer for storage in DB""" return int(num * 100)
def contains(text: str, pattern: str) -> bool: """Return a boolean indicating whether pattern occurs in text.""" assert isinstance(text, str), 'text is not a string: {}'.format(text) assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text) # ! Runtime = O(n), have to use contains ...
def _clean(v): """Convert parameters into an acceptable format for the API.""" if isinstance(v, (list, set, tuple)): return ",".join(str(i) for i in v) else: return str(v)
def fib(n): """Return the nth fibonacci number.""" a = 0 b = 1 for _ in range(n): a, b = b, a + b return a
def _text(e): """ Try to get the text content of this element """ try: text = e.text_content() except AttributeError: text = e return text.strip()
def is_valid_sudoku(sudokuBoard): """ :type sudokuBoard: list :rtype: bool """ seen = [] for i, row in enumerate(sudokuBoard): for j, c in enumerate(row): if c != '.': seen += [(c, j), (i, c), (i // 3, j // 3, c)] return len(seen) == len(set(seen))
def num_to_words(num, join=True): """ words = {} convert an integer number into words :param num: :param join: :return: """ units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] teens = ['', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',...
def is_valid_password_v1(password): """ Checks if a password is valid, with scheme 1 """ letter_count = sum([x == password["letter"] for x in list(password["password"])]) return password["low"] <= letter_count <= password["high"]
def iob1_to_iob2(tags): """ checked Check that tags have a valid IOB or IOB2/BIO format. Tags in IOB1 format are converted to IOB2. """ for i, tag in enumerate(tags): if tag == 'O': continue split = tag.split('-') if len(split) != 2 or split[0] not in ['I', 'B...
def from_cycle_notation(permutation, n): """ Convert a permutation from cycle notation to one-line notation. :param permutation: Permutation in cycle notation (list of tuples fo cycles in the permutation). :param n: Length of the permutation (needed since length 1 cycles are omitted in the cycle notati...
def getattribute(value, arg): """Gets an attribute of an object dynamically from a string name""" if hasattr(value, str(arg)): return getattr(value, arg)
def mm2pt(mm=1): """25.4mm -> 72pt (1 inch)""" return float(mm) * 72.0 / 25.4
def find_level_columns(columns): """This method finds level columns.""" return [e for e in columns if 'level' in e]
def string_or_default(message, default_message): """ Returns a given string, or a default message if the string is empty or invalid """ if (message is None or (not isinstance(message, str)) or len(message) < 1): return default_message else: return message
def sort_by_price_descending(res): """ res should be the return value of search (a list of Products as dictionaries) returns res as a sorted list of dicts by descending by price """ return sorted(res, key = lambda i: i["PriceInEuros"], reverse=True)
def rotate_point(xpoint, ypoint, angle, xcenter = 0, ycenter = 0, integer = False): """ Introduction ------------ This function will rotate a point in respect of another point (optionally given) by a certain angle. The outputs are the coordinates of the new point rotated I...
def int_to_string(x, byte=False): """Convert integer to string Parameters ---------- x: int Integer byte: bool Keep it bytes or not Returns ------- str (or bytes) Result Examples -------- >>> int_to_string(8387236825053623156) 'testtest' >>...
def _check_pronominal(infinitive): """ check if the infinitive is pronominal verb """ return infinitive.split()[0] == 'se' or infinitive.split("'")[0] == "s"
def polarization_to_success_probability(p, n): """ Inverse of success_probability_to_polarization. """ return p * (1 - 1 / 2**n) + 1 / 2**n
def auto_capitalize(text, state = None): """ Auto-capitalizes text. `state` argument means: - None: Don't capitalize initial word. - "sentence start": Capitalize initial word. - "after newline": Don't capitalize initial word, but we're after a newline. Used for double-newline detection. ...
def make_safe_name(name: str) -> str: """Return a name safe for usage in sql.""" return name.lower().replace(' ', '_')
def convert_mem(kmem, unit=None): """Returns an amount of memory in a human-readable string. :type kmem: int :param kmem: amount of memory in kB :rtype: str :return: same amount of memory formatted into a human-readable string """ k = 1024 if unit == 'K' or (unit is None and kmem < k)...
def prepare_template(temp): """Prepare template by reading the TEMPLATE and converting it to markdown Parameters ---------- temp : dict TEMPLATE (or its subfields) Returns ------- dict with default values and necessary """ out = {} for k, v in temp.items(): ...
def get_from_classad(name, class_ad, default=None): """ Get the value of the specified item from a job ClassAd """ value = default if name in class_ad: value = class_ad[name] return value
def _merge(listA, listB): """ Merges two list of objects removing repetitions. """ listA = [x.id for x in listA] listB = [x.id for x in listB] listA.extend(listB) set_ = set(listA) return list(set_)
def task_url_from_task_id(task_id: str) -> str: """ Transforms an Asana Task's object-id into an url referring to the task in the Asana app """ if not task_id: raise ValueError("task_url_from_task_id requires a task_id") return f"https://app.asana.com/0/0/{task_id}"
def is_valid_file_name_length(file_name, length): """ Check the file name length is valid :param file_name: The file name to be checked :param length: The length of file name which is valid :return: boolean """ return len(file_name) <= int(length)
def is_float(value: str) -> bool: """ Utility function to know whether or not a given string contains a valid float Args: value: string to check Returns: Boolean: True if string can be converted to float False otherwise """ try: float(value) ...
def _clear_empties(cleaned_data): """ FIXME: this is a work around because for some reason Django is seeing the new (empty) forms in the formsets as stuff that is to be stored when it really should be discarded. """ return [cd for cd in cleaned_data if cd.get('copy')]
def make_file_name(s): # adapted from # https://docs.djangoproject.com/en/2.1/_modules/django/utils/text/#slugify """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata, re s = unicodedata.normalize('NFKD', s).en...
def strip_prefix(name, split='_'): """ Strips prefix :param name: str, name to strip prefix of :param split: str, split character :return: str """ if not name.count(split): return name return split.join(name.split(split)[1:])
def swapNibbles(s): """ Swap nibbles of string s. """ # return ''.join([chr((ord(x) >> 4) | ((ord(x) & 0x0F) << 4)) for x in s]) sb = bytes.fromhex(s) return bytes([(x >> 4) | ((x & 0x0F) << 4) for x in sb])
def convCoord(v): """swizzle, the quake order is wacky. also scale by an arbitrary amount.""" scale = 1.0/15.0 return (v[1]*scale, v[2]*scale, v[0]*scale)
def id_from_url(url): """Get player id from URL.""" return url.strip("/").split("/")[-1]
def clean_line(str, delimiter): """Split a string into 'clean' fields. str the string to process delimiter the delimiter string to split 'line' with Returns a list of 'cleaned' field strings. Any fields that were initially zero length will be removed. If a field contains '\n' it isn't...
def _make_args_nokwargs(arg1, arg2, arg3): """Test utility for args no kwargs case""" return arg1 + arg2 + arg3
def new_chr(pos): """ Turn a number to the letter in that position in the alphabet """ return chr(pos + 96)
def alignTo(alignmentValue, bitPosition): """ Aligns the bit size to the given alignment value. :param alignmentValue: Value to align. :param bitPosition: Current bit position where to apply alignment. :returns: Aligned bit position. """ if bitPosition <= 0 or alignmentValue == 0: ...
def calc_process_time(t1, t2): """Calculates difference between times Args: t1 (float): initial time t2 (float): end time Returns: str: difference in times """ return str(t2 - t1)
def get_fashion_mnist_labels(labels): """Return text labels for the Fashion-MNIST dataset.""" text_labels = [ 't-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot'] return [text_labels[int(idx)] for idx in labels]
def not_found(environ, start_response): """Called if no URL matches.""" start_response('404 NOT FOUND', [('Content-Type', 'text/plain')]) return [environ.get('PATH_INFO', '').lstrip('/')]
def add_outgrads(prev_g, g): """Add gradient contributions together.""" if prev_g is None: return g return prev_g + g
def get_private_endpoint(id: str, guid: str) -> str: """Get remote endpoint for delivering private payloads.""" _username, domain = id.split("@") return "https://%s/receive/users/%s" % (domain, guid)
def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ try: color = 'red' if val < 0 else 'black' except TypeError: color = 'black' return 'color: %s' % color
def sum_of_sequence(n): """ Using N(N+1)/ 2 """ if not input: return 0 else: return (n*(n+1))/2
def remove_stopwords(annotations, stop_words=[]): """ Recibe una lista de textos y stopwords, luego elimina las stopwords para cada elemento de la lista de textos """ return [' '.join([word for word in ann.split() if word not in stop_words]) for ann in annotations]
def capitalize(arg): """Capitalize or upper depending on length. >>> capitalize('telia') 'Telia' >>> capitalize('free peering') 'Free peering' >>> capitalize('ix') 'IX' >>> capitalize('man') 'MAN' """ if len(arg) <= 3: return arg.upper() return arg.capitalize()
def diff_last_filter(trail, key=lambda x: x['pid']): """ Filter out trails with last two key different """ return trail if key(trail[-1]) != key(trail[-2]) else None
def tuples_to_dict(kvw_tuples, colnums=(0, 1)): """Given a list of k,v tuples, get a dictionary of the form k -> v :param kvw_tuples: list of k,v,w tuples (e.g. [(k1,v1,a1), (k2,v2,a2), (k3,v3,a3), (k1,v4,a4)] :param colnums: column numbers :return: a dict; something like {k1: v4, k2: v2, k3: v3} (note...
def validate_nodes_number(nodes_number: int) -> int: """ Check whether a number of nodes is sufficient to detrend the data. Parameters ---------- nodes_number : int The number of nodes. Returns ------- int The number of nodes. Raises ------ ValueError ...
def labels_after_1(circle): """ >>> labels_after_1({8: 3, 3: 7, 7: 4, 4: 1, 1: 9, 9: 2, 2: 6, 6: 5, 5: 8}) '92658374' >>> circ = meh(EXAMPLE_INPUT) >>> cur = int(EXAMPLE_INPUT[0]) >>> for m in range(100): ... cur = make_move(circ, cur) ... >>> labels_after_1(circ) '67384529' ...
def escape_trailing__(string: str) -> str: """ Returns the given string with trailing underscores escaped to prevent Sphinx treating them as references. .. versionadded:: 0.8.0 :param string: """ if string.endswith('_'): return f"{string[:-1]}\\_" return string
def str_or_na(string): """Return the string or "na". """ try: return string except: return "na"
def equivalent_viscous_damping(mu, mtype="concrete", btype="frame"): """ Calculate the equivalent viscous damping based on the ductility and structural type. :param mu: Displacement ductility :param mtype: material type :param btype: building type (e.g. frame or wall) :return: """ pie = ...
def _match_cookie(flow_to_install, stored_flow_dict): """Check if a the cookie and its mask matches between the flows.""" cookie = flow_to_install.get("cookie", 0) & flow_to_install.get("cookie_mask", 0) cookie_stored = stored_flow_dict.get("cookie", 0) & flow_to_install.get( "cookie_mask", 0 ) ...
def quote_list(the_list): """Jinja helper to quote list items""" return ["'%s'" % element for element in the_list]
def type_boost(doctype, boost_factor): """Helper function to boost results from particular data stores""" return { "boost_factor": boost_factor, "filter": { "type": { "value": doctype } } }
def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy. http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression """ z = x.copy() z.update(y) return z