content
stringlengths
42
6.51k
def separate_ctrlpts_weights(ctrlptsw): """ Divides weighted control points by weights to generate unweighted control points and weights vector. This function is dimension agnostic, i.e. control points can be in any dimension but the last element of the array should indicate the weight. :param ctrlpts...
def check_for_commands(string: str): """ Checks the message for a string command :param string: :return: """ prefix = "/" commands = ["restart", "update", "showrooms"] pr_cmd = [f"{prefix}{x}" for x in commands] for cmd in pr_cmd: if cmd in string or cmd == string: ...
def parse_version_token(s): """Return a list of one or two tokens depending on the version token type. It is accepted to have a number, a character or a number followed by a character, e.g. "5" -> ["5"], "a" -> ["a"] or "5a" -> ["5", "a"] are acceptable.""" if len(s) > 1 and s[-1].isalpha()...
def escape_tab(s: str) -> str: """Replaces each tab character (\\t) in the input with \\\\t""" return s.replace('\t', '\\t')
def replace_num(s): """Remueve los numeros de los tweets""" for i in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]: s = s.replace(i, "") return s
def allowedObject(typeOfObject): """Returns True if the object type is allowed, False otherwise.""" if typeOfObject == 'car': return True elif typeOfObject == 'person': return True elif typeOfObject == 'bicycle': return True elif typeOfObject == 'bus': return True ...
def quadratic_cutoff(r_cut: float, ri: float, ci: float): """A quadratic cutoff that goes to zero smoothly at the cutoff boundary. Args: r_cut (float): Cutoff value (in angstrom). ri (float): Interatomic distance. ci (float): Cartesian coordinate divided by the distance. Returns: ...
def num_inter_memory_bonds(n_bp, memory_range, n_template): """Calculate the expected number of bonds for inter-strand associative memory force Args: n_bp (int): number of basepairs in the system memory_range (int): size of the memory n_template (int): number of templates used as memori...
def add_to_list(str_to_add, round_three): """ Add new candidates to the queue """ if str_to_add not in round_three: round_three.append(str_to_add) return round_three.index(str_to_add)
def checkdist(conddist): """ Check user input type if distribution type selected for generating conditions. Parameters ---------- conddist : str or NoneType condition distribution name Returns ------- str or None """ if conddist is None: return None elif co...
def s2B(ss): """ Switch string and bytes. """ if type(ss) == bytes : return ss return bytes([ord(c) for c in ss])
def is_latin_1_encodable(value: str) -> bool: """Header values are encoded to latin-1 before sending.""" try: value.encode("latin-1") return True except UnicodeEncodeError: return False
def make_max_dict(group_str): """We need to create mock MAX data at multiple points in these tests""" return { 'cas:serviceResponse': { 'cas:authenticationSuccess': { 'cas:attributes': { 'maxAttribute:Email-Address': 'test-user@email.com', ...
def make_printable(string): """Makes a surrogate-escaped string printable. Args: string: Unicode string with surrogate code points. Returns: Unicode string having surrogates replaced by the replacement character. """ return ''.join('\ufffd' if 0xd800 <= ord(c) < 0xe000 else c for c in string)
def sort_seconds(timestamps): """ Sorts a list of 2-tuples by their first element """ return sorted(timestamps, key=lambda tup: tup[0])
def fold2Up(data, names, normed = None, **kargs): """ good for normalised illumina data, returns the fold2up/down data """ if normed: norm_value = data[normed] for c in data: if c != normed: normed_data = (data[c] / data[normed]) # this is gree...
def TimeFormatter(milliseconds: int) -> str: """ Adjust the time from milliseconds to the right measure. milliseconds (``int``): Number of milliseconds. SUCCESS Returns the adjusted measure (``str``). """ seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds =...
def traditional_icr_equation(tdd): """ Traditional ICR equation with constants fit to Jaeb dataset """ a = 308.76 return a / tdd
def euler_step(f, x0, t0, t1): """ One time step of Euler method f : function dx_dt(t0, x0) x0 : initial condition t0 : this step time t1 : next step time """ # time step delta_t = t1 - t0 # slope s1 = f(t0, x0) # next step x1 = x0 + s1 * delta_t return x1
def create_nd_array(shape): """create n-dimensional array filled with 0""" if len(shape) == 0: return 0 res = [] for _ in range(shape[0]): res.append(create_nd_array(shape[1:])) return res
def get_textual_float(value, format = '%.2f'): """Get textual representation of floating point numbers and accept None as valid entry format is a string - default = '%.2f' """ if value is None: return 'None' else: try: float(value) except: # May ...
def _separate_keyword(line): """Split the line, and return (first_word, the_rest).""" try: first, rest = line.split(None, 1) except ValueError: first = line.strip() rest = '' return first, rest
def _force_dict(value): """If the value is not a dict, raise an exception.""" if value is None or not isinstance(value, dict): return {} return value
def modify_attribute(words, key, value): """Modify dict attribute for a list of words""" for word in words: word[key] = value return words
def get_extension(packaging): """ We only care for certain artifacts extension/packaging/classifier. Maven has some intricate interrelated values for these fields type, extension, packaging, classifier, language See http://maven.apache.org/ref/3.5.4/maven-core/artifact-handlers.html These ...
def is_telemarketer_number(number): """ Telemarketers' numbers have no parentheses or space, but they start with the area code 140. """ return len(number) >= 3 and number.startswith("140")
def find_lcs(s1, s2): """find the longest common subsequence between s1 ans s2""" m = [[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)] max_len = 0 p = 0 for i in range(len(s1)): for j in range(len(s2)): if s1[i] == s2[j]: m[i + 1][j + 1] = m[i][j] + 1...
def pairs_lin(k, arr): """ Runtime: O(n) Adapted from: ardendertat.com/2011/09/17/programming-interview-questions-1-array-pair-sum """ if len(arr) < 2: return [] output = seen = [] for n in arr: partner = k - n if partner in seen: output.append([n, pa...
def fibonacci(n): """Computes the nth Fibonacci number. For example:: >>> map(fibonacci,range(10)) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] Utilizes modified code from `this answer on Stack Overflow <http://stackoverflow.com/a/14782458/786020>`_ based upon the concept explained `here on Wikip...
def squared_call(fn, arg): """Call fn on the result of calling fn on arg""" return fn(fn(arg))
def binary_search(l:list, item): """Perform binary search on a homogenous list for an item and return it's location. Args: l (list): the homogenous list to be searched item (): the item to look for in the list Returns: int: index location of item in list or `None` """ ...
def reduce_score(score): """Convert tuple into 1-dimension score.""" moves, pushes, steps = score return moves + pushes + steps
def solution(E, L): # write your code in Python 2.7 """ default fee = 2 first hour or partial hour fee = 3 after successive full or patial hour or full = 4 E 10:00, L 13:21 = 2 + 3 + 4*2 + 4 =17 """ # edge cases # if E or L is not defined, just default fee if not(E) or not(L): r...
def encode_csv_string(text): """ Encode a string to be used in CSV file Args: text: String to encode Returns: Encoded string, including starting and ending double quote """ res = ['"'] for c in text: res.append(c) if c == '"': res.append('"') res...
def _index(i, size, Cartesian=True): """If Cartesian=True, index 0 is swapped with index 1.""" if Cartesian: if i == 1: return 0 if i == 0: if size >= 2: return 1 return i
def int_to_chain(i,base=62): """ int_to_chain(int,int) -> str Converts a positive integer to a chain ID. Chain IDs include uppercase characters, numbers, and optionally lowercase letters. i = a positive integer to convert base = the alphabet size to include. Typically 36 or 62. """ if i ...
def translate_precision_to_integer(precision: str) -> int: """ This function translates the precision value to indexes used by wikidata :param precision: :return: """ if isinstance(precision, int): return precision precision_map = { "gigayear": 0, "gigayears": 0, "100 megayears": 1, "100 megayear": 1, ...
def _get_table_rank_and_score( scored_hits, table_id, ): """Returns rank and score of 'table_id'.""" for rank, (current_table_id, score) in enumerate(scored_hits): if current_table_id == table_id: return rank + 1, score return None
def mask_dict_password(dictionary, secret="***"): """Replace passwords with a secret in a dictionary.""" d = dictionary.copy() for k in d: if "password" in k: d[k] = secret return d
def in_sequence_bool(sequence, possible_triplet): """ To see whether a set of triplets ie [1,2,3] in contained in the sequence ie. if triplets is [1,2,3], then sequence [4,1,3,2] should return True ie. if triplets is [1,2,3], then sequence [4,1,5,2] should return False """ sequencex = sequence.c...
def match_submit(json): """Checks the json db_instances matches the submit object.""" # Check the report has an id assert 'id' not in json # Check the report has a upload date assert 'upload_datetime' in json assert type(json['upload_datetime']) is str # Check the report has a resource_ty...
def grfcbk_size(args): """ Grammar rule function callback: **size**. This function will count the size of first item in argument list. :param list args: List of function arguments. :return: Size of the first item in argument list. :rtype: int """ return len(args[0])
def find_disjoint_subsequences(li, seq): """ Returns a list of tuples (i,j,k,...) so that seq == (li[i], li[j], li[k],...) Greedily find first tuple, then second, etc. """ subseqs = [] cur_subseq_inds = [] for (i_el, el) in enumerate(li): if el == seq[len(cur_subseq_inds)]: ...
def format_stringify_list(input_list): """ Function to format features when merging multiple feature attributes Parameters ---------- input_list : TYPE Description Returns ------- TYPE Description """ return ", ".join(str(l) for l in input_list)
def extract_entity_names(item): """Docstring""" entity_names = [] # if hasattr(item, 'label') and item.label: # if item.label() == 'NE': # entity_names.append(' '.join([child[0] for child in item])) # else: # for child in item: # entity_names.extend(...
def translate(rna_sequence): """ Compute the protein that will be produced by the given RNA sequence. Parameters ---------- rna_sequence : string The RNA strand we are evaluating. Returns ------- protein : string The resulting protein from evaluating the codons in the R...
def isprop(v): """ Test if attribute is a property """ return isinstance(v, property)
def parseContent(wordCounter, content): """ Returns updated wordCounter using fileContent """ # read every line for line in content: # and every word in them for word in line.split(): if word.lower() in wordCounter: # if word is already in dictionary, add 1 ...
def get_cell_type_from_inset_begin_line(begin_line): """Note this depends on the naming convention in the .module files. Returns a tuple (<basictype>,<language>). For example, ("Standard", "Python").""" split_line = begin_line.split(":") language = split_line[-1].strip() basic_type = split_line...
def getEmptyVenues(timetable, venueList): """ Return a list of empty venues Args: timetable: A list of TimetableEntry to search in venueList: A list containing all valid venues Returns: Returns a list of all venues that are empty """ # Creates a deep copy of the list empty = venueList[:] # Remove venue...
def selections_equal(selection1, selection2): """Whether the selections are equivalent""" # To do: Merge overlapping regions? selection1 = sorted(selection1) selection2 = sorted(selection2) if len(selection1) != len(selection2): return False for index in range(0, len(selection1)): ...
def parent(tree, node): """ returns false if node is not in the tree """ if not isinstance(tree, tuple): return False subtrees = tree[1] if node in subtrees: return tree for subtree in subtrees: p = parent(subtree, node) if p: return p return False
def remove_zips_and_metas(data): """ Function to remove all the zip files from the made database.json """ if not isinstance(data, (dict, list)): return data if isinstance(data, list): return [remove_zips_and_metas(val) for val in data] return {k: remove_zips_and_metas(val) fo...
def counts(bigram_list): """Takes a list like ['ae', 'bg', 'ae, 'sd'] And outputs number of occurences of things so [2, 1, 1]""" stuff_dict = {} for thing in bigram_list: try: stuff_dict[thing] += 1 except KeyError: stuff_dict[thing] = 1 comp = [stu...
def gen_replacement_dict(old_config, new_config): """Create a pymatgen replacement dict based on old and new sublattice configurations. Shapes of the config lists must match. Parameters ---------- old_config : list DFTTK style configuration that will be replaced new_config : list ...
def update_hand(hand, word): """ Does NOT assume that hand contains every letter in word at least as many times as the letter appears in word. Letters in word that don't appear in hand should be ignored. Letters that appear in word more times than in hand should never result in a negative count...
def search_internal_lists_for_matching_alias(intext, inlist): """ Returns an object or none if none :param intext: :param inlist: :return: """ existing_obj = None for item in inlist: # print('searching for ') # print(intext) # print(item) if 'properties' i...
def set_find(set_nodes, i): """ Set find implementation with path compression :param set_nodes: dictionary where key is node id and value is set containing node :param i: id of node Returns ------- id of the set containing the node i """ if i != set_nodes[i]: set_nodes[i] = set_find(set_nodes, s...
def is_leap_year(year): """ Returns whether a year is a leap year - Leap years are any year that can be exactly divided by 4 - Except if it can be divided exactly by 100 then it isn't - But if it can be divided exactly by 400 then it is a leap year """ if (year % 4 == 0 and year ...
def matrix_max(matrix): # SYFPEITHI NORMALIZATION """Returns the maximum attainable score for a pssm""" return sum([ max(value.values()) for _, value in matrix.items() ])
def task_descriptor_world(task): """ Return task descriptor for hello/goodbye task. """ return "{world_name}".format(**task)
def mulmatvec3x3(m, vect): """ This function returns a 3D vector which consists of the 3D input vector multiplied by a 3x3 matrix. :rtype: double iterable :return: 3D vector :type m: double iterable :param m: The matrix to multiply :type vect: double iterable ...
def merge_dicts(*args): """Merge multiple dictionaries in a new one treating None as an empty dictionary. merge_dicts(dict1, [dict2 [...]]) -> dict1.update(dict2);dict1.update ... Parameters ---------- *args : dict-like Returns ------- dict Example ------- >>> d1 = d...
def h2h_match_result(score1, score2): """ >>> h2h_match_result(5, 1) == 5. / 6 True >>> h2h_match_result(0, 1) == 2.5 / 6 True >>> h2h_match_result(3, 1) == 4. / 6 True """ draws_add = (6. - (score1 + score2)) / 2 return float(score1 + draws_add) / 6
def generate_single_strategy_profile(player_configuration, strategy_config): """ Returns a strategy profile with a single strategy :return: None """ return {reporter['name']: strategy_config for reporter in player_configuration}
def requires_replacement(changeset): """Return the changes within the changeset that require replacement. Args: changeset (list): List of changes Returns: list: A list of changes that require replacement, if any. """ return [r for r in changeset if r["ResourceChange"]["Replacement...
def extract_field_names(dict_list): """Returns a sorted list of field names from a dictionary list > extract_field_names([{'a': 1, 'b': 2}, {'a': 3, 'c': 4}]) ['a', 'b', 'c'] """ field_names = [] for row_dict in dict_list: field_names += row_dict.keys() field_names = list(set(field_n...
def compute_cutoff_threshold(C: list, threshold: float): """ Algorithm 1 of the paper "Automatic Discovery of Attributes in Relational Databases" from M. Zhang et al. [1] This algorithm computes the threshold of a column that determines if any other column is to be considered its neighbour. Paramet...
def box_combine(o, s, box1, box2): """ args: box1 : (x1_0, y1_0, x1_1, y1_1) box2: (x2_0, y2_0, x2_1, y2_1) return: dict["1_2":(min(x1_0,x2_0),min(y1_0,y2_0),max(x1_1,x2-1),max(y2_1,y2_2))] """ name = '{}_{}'.format(o, s) combine = (min(box1[0], box2[0]), min(box1[1], b...
def make_config_string(config, key_len=4, max_num_key=4): """ Generate a name for config. :param config: :param key_len: the length of printed key :return: """ str_config = '' num_key = 0 for k, v in config.items(): if num_key < max_num_key: str_config += '[' + k[:key...
def calcScore(locNum, contactMat, numLoc): """Calculate directionality index for locus. See Dixon 2012 supplemental.""" a = 0 #initialize b = 0 aCount = 0 bCount = 0 avg_a = 0 avg_b = 0 for i in range(locNum-numLoc, locNum): #upstream a += contactMat[locNum][i] aCount +=...
def update_http_headers(resource_data, response_headers): """ Updates resource data dict with AWS entities if matching header found. :param resource_data: event's resource data dict :param response_headers: response headers from HTTP request :return: update resource data dict """ for header_...
def curve_score(curve): """Calculate a score for a curve by which they are sorted""" # this should be optimized return sum(curve)
def lorentzian(x, gamma, mu, A, B): """A is the maximum of the peak, mu the center, and gamma the FWHM. B is background.""" return 1 / (1 + (2 * (x - mu) / gamma) ** 2) * A + B
def calculate_svg_sizes(count): """ Calculate the size of the green half based off the length of count """ text = str(count) sizes = { 'width': 80, 'recWidth': 50, 'textX': 55 } if len(text) > 5: sizes['width'] += 6 * (len(text) - 5) sizes['recWidth'] += 6 * (...
def set_nested_dict_value(input_dict, key, val): """Uses '.' or '->'-splittable string as key and returns modified dict.""" if not isinstance(input_dict, dict): # dangerous, just replace with dict input_dict = {} key = key.replace("->", ".") # make sure no -> left split_key = key.split...
def rotate_matrix(data): """From give matrix of data, transpose it""" new_matrix = [] for i in range(len(data[0])): new_matrix.append([data[j][i] for j in range(len(data))]) return new_matrix
def hash_side_effect(value): """Side effect value.""" if "mail_none.gif" in value: return "633d7356947eec543c50b76a1852f92427f4dca9" else: return "133d7356947fec542c50b76b1856f92427f5dca9"
def xgcd(a, b): """return (g, x, y) such that a*x + b*y = g = gcd(a, b)""" x0, x1, y0, y1 = 0, 1, 1, 0 while a != 0: (q, a), b = divmod(b, a), a y0, y1 = y1, y0 - q * y1 x0, x1 = x1, x0 - q * x1 return b, x0, y0
def to_camel_case(snake_str: str) -> str: """ Covert a string from snake case to camel case eg. to_camel_case('snake_case') -> 'snakeCase' """ components = snake_str.split('_') return components[0] + ''.join(x.title() for x in components[1:])
def _subject(subject): """ Returns a query item matching "subject". Args: subject: The subject of the message. Returns: The query string. """ return f"subject:{subject}"
def remove_image_markdown(string): """ Remove leading image markdown by bracket detection Assumes string is in one of two forms: 1) [name](url.png) some text after a space 2) some text without markdown Args: string (str): string which may include leading image markdown Retur...
def carrier_concentration( electron_conc: float, hole_conc: float, intrinsic_conc: float, ) -> tuple: """ This function can calculate any one of the three - 1. Electron Concentration 2, Hole Concentration 3. Intrinsic Concentration given the other two. Examples - >>> carrier_...
def interval_intersect(a, b, c, d): """ *** write a proper docstring here *** *** add five more testcases here *** """ # *** YOUR CODE HERE *** return False
def get_tri_from_course(course, courses): """ Given a courses dict, return the trimester of the :param course """ for tri in courses: for _course in courses[tri]: if course == _course: return tri
def string_to_none_bool_int_float_complex(string): """Convert a string into :data:`None`, :data:`True`, :data:`False`, :class:`int`, :class:`float` or :class:`complex`. Returns `string` if it cannot be converted to any of these types. 0 and 1 get converted to an integer not a boolean. """ su =...
def strip_url(x: str) -> str: """Return the name of the schema entity after stripping url. Args: x (str): URL of the enitity. Returns: str: The name of entity. """ x_strip = str(x).split('/')[-1] return x_strip
def get_ratio(numerator, denominator): """Get ratio from numerator and denominator.""" return ( 0 if not denominator else round(float(numerator or 0) / float(denominator), 2) )
def is_from(category, symbol): """Checks if the symbol is from the category given. Args: category (dict): The dictionary of the category to check. symbol (str): The symbol or word given to analyze. Returns: bool: Whether the symbol is part of the category given. """ tr...
def email_escape(email): """ Escape email to a safe string of kubernetes namespace """ safe_email = email.replace("@", "-") safe_email = safe_email.replace(".", "-") safe_email = safe_email.replace("_", "-") return safe_email
def convertSentenceToWords(text, index): """ Converts a sentence given into a list of words. Parameters: text (string): a sentence Returns: words (list): list of the sentence's words """ words = text.split() for i in range (0, index): words.pop(0) return words
def count_query(project,dataset,tablename,condition): """ Function to process query for count process """ if isinstance(tablename, str): pass else: raise ValueError("Tablename should be a String") if isinstance(dataset, str): pass else: raise ValueError("Tab...
def aset(L): """answer""" if L == []: return [[]] x = aset(L[1:]) return x + [[L[0]] + y for y in x]
def score(a, b): """score dna as match/mismatch""" if a == b: return 1 return -1
def str_bool(x): """Implementation of `str_bool`.""" if x == "": return False return True
def sentiment(text): """ text should be processed before predicting sentiment """ print(text) # sent = classify.sentiment(text) """ Once sentiment is predicted it should be appended to the tweet body """ """ After preparing the tweet it should be stored into ElasticSearch """ return text
def get_fancylabel_Nd(fromNd, toNd): """ :param fromNd: :param toNd: :return: """ if fromNd > 0: varNameN = 'N$_{%d<d<%d}$' % (fromNd, toNd) else: varNameN = 'N$_{d<%d}$' % toNd return varNameN
def sliceAlign(align,region,sites=False): """Return a region of the alignment where region is (start, end) OR if sites is True then include all sites in region (not range)""" if region is None: return align elif sites: return align.map(lambda seq: ''.join([seq[r] for r in region])) e...
def _add_free_prices(course): """ Adds a free price to all runs Args: course (Course): the course to update Returns: Course: updated course """ for run in course["runs"]: run["prices"].append({"price": 0}) return course
def width(version): """ Calculates the width of a version The width of version 1 is 21, version 2 is 25, 3 is 29 etc. """ return 17 + 4 * version