content
stringlengths
42
6.51k
def nodeconfig(nodeconfig_line): """ converts to nodeconfig """ config = {} tokens = nodeconfig_line.split('; ') for token in tokens: pairs = token.split('=') if len(pairs) > 1: config[pairs[0]] = pairs[1] return config
def google_list_style(style): """finds out whether this is an ordered or unordered list""" if 'list-style-type' in style: list_style = style['list-style-type'] if list_style in ['disc', 'circle', 'square', 'none']: return 'ul' return 'ol'
def headers(questions): """ Generate the headers for the CSV file - take an array of questions. The order is important - Each question id is a column header - Paired with the index+1 of it's position in the array - Example: 43:SQ3-1d - SQ3-1d is the old question id - 43 is it's number on...
def solution(n: int = 1000) -> int: """ returns number of fractions containing a numerator with more digits than the denominator in the first n expansions. >>> solution(14) 2 >>> solution(100) 15 >>> solution(10000) 1508 """ prev_numerator, prev_denominator = 1, 1 ...
def payloadDictionary(payload, lst): """creates payload dictionary. Args: payload: String SQL query lst: List of Strings keywords for payload dictionary Returns: dikt: dictionary dictionary using elements of lst as keys and payload a...
def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: An integer. bits: Maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return ...
def next_word_max_solution(prev_seq, counts, N): """Returns the word with the highest occurence given a word sequence :param prev_seq: :param counts: :param N: :returns max_successor """ token_seq = " ".join(prev_seq.split()[-(N-1):]) # SOLUTION: max_successor = max(counts[to...
def is_nursery_rule_path(path: str) -> bool: """ The nursery is a spot for rules that have not yet been fully polished. For example, they may not have references to public example of a technique. Yet, we still want to capture and report on their matches. The nursery is currently a subdirectory of th...
def riemann_sum(func, partition): """ Compute the Riemann sum for a given partition Inputs: - func: any single variable function - partition: list of the form [(left, right, midpoint)] Outputs: - a float """ return sum(func(point) * (right - left) for left, right, point...
def source_page(is_awesome) -> str: """ Returns an awesome string Args: is_awesome (bool): is SourcePage awesome? """ if is_awesome: return f"{is_awesome}! SourcePage is awesome!" return f"{is_awesome}! Nah, SourcePage is still awesome!"
def remove_prefix(state_dict, prefix): """ Old style model is stored with all names of parameters sharing common prefix 'module.' """ # print('remove prefix \'{}\''.format(prefix)) f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x return {f(key): value for key, value in state_dict.item...
def getinrangelist(inputlist,minval,maxval): """creates a binary list, indicating inputlist entries are between (inclusive) the minval and maxval""" inrangelist=[1 if maxval>=i>=minval else 0 for i in inputlist] return inrangelist
def convert_eq(list_of_eq): """ Convert equality constraints in the right format to be used by unification library. """ lhs = [] rhs = [] for eq in list_of_eq: lhs.append(eq.lhs) rhs.append(eq.rhs) return tuple(lhs), tuple(rhs)
def _drop_label_from_string(label_string: str, search_label: str): """ Mask labels with Booleans that appear in row """ valid_labels = [] for label in label_string.split(' '): if search_label == label: continue valid_labels.append(label) return ' '.join(valid_labels)
def update_nested_dictionary(old, new): """ Update dictionary with the values from other dictionary. Recursively update any nested dictionaries if both old and new values are dictionaries. :param old: Old dictionary that will be updated :type old: dict :param new: New dictionary that contains t...
def marker_name(name): """Returns a marker filename for an external repository.""" return "@{}.marker".format(name.replace("//external:", ""))
def music(music=True): """Enables, or disables, the in-game music. Useful if you want to use an MSU-1 soundtrack instead. Keyword Arguments: music {bool} -- If true, music is enabled. If false, the music id disabled. (default: {True}) Returns: list -- a list of dictionaries indica...
def decode_base_qual(raw_base_qual: bytes, offset: int = 33) -> str: """Decode raw BAM base quality scores into ASCII values Parameters ---------- raw_base_qual : bytes The base quality section of a BAM alignment record as bytes eg the output from pylazybam.bam.get_...
def citationContainsDOI(citation): """ Checks if the citation contains a doi """ if citation.startswith("doi:"): return True elif citation.startswith("@doi:"): return True elif citation.startswith("[@doi"): return True else: return False
def transpose(m): """transpose(m): transposes a 2D matrix, made of tuples or lists of tuples or lists, keeping their type. >>> transpose([]) Traceback (most recent call last): ... IndexError: list index out of range >>> transpose([[]]) [] >>> transpose([1,2,3]) Traceback (most...
def protect_special_chars(lines): """Add \ in front of * or _ so that Markdown doesn't interpret them.""" for i in range(len(lines)): if lines[i][0] in ['text', 'list', 'list-item']: protectedline = [] for c in lines[i][1]: if c in '_*': protec...
def _find(s: str, ch: str) -> list: """ Finds indices of character `ch` in string `s` """ return [i for i, ltr in enumerate(s) if ltr == ch]
def is_valid_strategy(strategy): """A valid strategy comes in pairs of buys and sells.""" cumsum = 0 for num in strategy: cumsum += num if cumsum > 0: return False elif cumsum < -1: return False return True
def node_type(node): """ Node numbering scheme is as follows: [c1-c309] [c321-c478] old compute nodes (Sandy Bridge) [c579-c628],[c639-c985] new compute nodes (Haswell) -- 50 + 346 Special nodes: c309-c320 old big memory nodes (Sandy Bridge) c629-c638 new big memory nodes (Haswell) -- 10 c577,c578 old huge mem...
def eye_to_age(D_eye): """Inverts age_to_eye_diameter Args: D_eye (float): Diameter of Eyepiece (mm); default is 7 mm Returns: age (float): approximate age """ if D_eye > 7.25: age = 15 elif D_eye <= 7.25 and D_eye > 6.75: age = 25 elif D_eye <= 6.75 and...
def generate_targets_dict_for_comparison(targets_list): """ Generates a dict which contains the target name as key, and the score '1.00' and a p-value 'foo' as a set in the value of the dict. This dict will be used for the targets comparison """ targets_dict = {} for target in targets_li...
def _pretty(name: str) -> str: """ Make :class:`StatusCode` name pretty again Parameters ----------- name: [:class:`str`] The status code name to make pretty Returns --------- :class:`str` The pretty name for the status code name given """ return name.replace("_"...
def bindings_friendly_attrs(format_list): """ Convert the format_list into attrs that can be used with python bindings Python bindings should take care of the typing """ attrs = [] if format_list is not None: if isinstance(format_list, list): attrs = format_list elif ...
def tail(lst): """ tail(lst: list) 1 to len of a list args: a list => eg: [1,2,3] return: a list => [2,3] """ return lst[1:]
def split(input_list): """ Splits a list into two pieces :param input_list: list :return: left and right lists (list, list) """ input_list_len = len(input_list) midpoint = input_list_len // 2 return input_list[:midpoint], input_list[midpoint:]
def tumor_type_match(section, keywords, match_type): """Process metadata function.""" for d in section: if not keywords: d[match_type] = "null" else: d[match_type] = "False" for k in keywords: if k in d["db_tumor_repr"].lower(): d[match...
def add_w_to_param_names(parameter_dict): """ add a "W" string to the end of the parameter name to indicate that the parameter should over-write up the chain of stratification, rather than being a multiplier or adjustment function for the upstream parameters :param parameter_dict: dict the ...
def check_for_output_match(output, test_suite): """Return bool list with a True item for each output matching expected output. Return None if the functions suspects user tried to print something when they should not have. """ output_lines = output.splitlines() if len(output_lines) != len(test_...
def next_pow_two(max_sent_tokens): """ Next power of two for a given input, with a minimum of 16 and a maximum of 512 Args: max_sent_tokens (int): the integer Returns: int: the appropriate power of two """ pow_two = [16, 32, 64, 128, 256, 512] if max_sent_tokens <= pow_...
def tokenize_stories(stories, token_to_id): """ Convert all tokens into their unique ids. """ story_ids = [] for story, query, answer in stories: story = [[token_to_id[token] for token in sentence] for sentence in story] query = [token_to_id[token] for token in query] answer ...
def remove_num(text): """ Function to clean JOB_TITLE and SOC_TITLE by removing digits from the values """ if not any(c.isdigit() for c in text): return text return ''
def unpad(data): """Remove PKCS#7 padding. This function remove PKCS#7 padding at the end of the last block from `data`. :parameter: data : string The data to be unpadded. :return: A string, the data without the PKCS#7 padding. """ array = bytearray() array.extend(data) ...
def can_import(module_name): """Check if module can be imported. can_import(module_name) -> module or None. """ try: return __import__(module_name) except ImportError: return None
def make_cache_key(question, docid): """Constructs a cache key using a fixed separator.""" return question + '###' + docid
def myavg(a, b): """ tests this problem >>> myavg(10,20) 15 >>> myavg(2,4) 3 >>> myavg(1,1) 1 """ return (a + b) / 2
def try_parse_int(s, base=10, val=None): """returns 'val' instead of throwing an exception when parsing fails""" try: return int(s, base) except ValueError: return val
def h(n): """ assume n is an int >= 0 """ answer = 0 s = str(n) for c in s: answer += int(c) return answer
def applyCompact(a, cops): """ Apply compact ops to string a to create and return string b """ result = [] apos = 0 for op in cops: if apos < op[1]: result.append(a[apos:op[1]]) # equal if op[0] == 0: result.append(op[3]) apos = o...
def convertCharToInt(strs: list) -> list: """pega uma lista de caracteres e converte em uma lista de inteiros""" for x in range(len(strs)): strs[x] = ord(strs[x]) return strs
def grid_search_params(params): """ Given a dict of parameters, return a list of dicts """ params_list = [] for ip, (param, options) in enumerate(params.items()): if ip == 0: params_list += [{param: v} for v in options] continue _params_list = [dict(_) f...
def deterministic(v, u): """ Generates a deterministic variate. :param v: (float) deterministic value. :param u: (float) rnd number in (0,1). :return: (float) the ChiSquare(n) rnd variate. """ # u is intentionally unused return v
def mass_surface_solid( chord, span, density=2700, # kg/m^3, defaults to that of aluminum mean_t_over_c=0.08 ): """ Estimates the mass of a lifting surface constructed out of a solid piece of material. Warning: Not well validated; spar sizing is a guessed scaling and not bas...
def left_circ_shift(x: int, shift: int, n_bits: int) -> int: """ Does a left binary circular shift on the number x of n_bits bits :param x: A number :param shift: The number of bits to shift :param n_bits: The number of bits of x :return: The shifted result """ mask = (1 << n_bits) - 1 ...
def vis8(n): # DONE """ OO OO OOO OOO OOO OOOO Number of Os: 2 4 7""" result = '' for i in range(1, n + 1): result += 'O' * (n) if i == n: result += 'O\n' else: result += '\n' return result
def _get_tissue(x): """ It extracts the tissue name from a filename. """ if x.endswith("-projection"): return x.split("spredixcan-mashr-zscores-")[1].split("-projection")[0] else: return x.split("spredixcan-mashr-zscores-")[1].split("-data")[0]
def is_palindrome(string): """Solution to exercise C-4.17. Write a short recursive Python function that determines if a string s is a palindrome, that is, it is equal to its reverse. For example, "racecar" and "gohangasalamiimalasagnahog" are palindromes. """ n = len(string) def recurse(id...
def value2string(val): """ to convert val to string """ if val is None: return "" else: return str(val)
def to_month_number(month_name): """ Convert English month name to a number from 1 to 12. Parameters ---------- month_name : str Month name in English Returns ---------- month_number: int 1-12 for the names from January to December, 0 for other inputs ...
def choose_in(keys, values, choices): """" Return the values corresponding to the choices :param keys: list of keys :param values: list of values :param choices: list of choices """ dictionary = dict(list(zip(keys, values))) return [dictionary[key] for key in choices]
def same_rows(rows_list_1, rows_list_2): """Compare DF rows represented as lists of tuples ('records'). Checks that the lists contain the same tuples (possibly in different orders). """ return sorted(rows_list_1) == sorted(rows_list_2)
def vector(b,e): """Vector Subtraction function. Parameters ---------- v : list First 3D vector. e : list Second 3D vector. Returns ------- tuple Returns the vector of e - v. Examples -------- >>> import numpy as np >>> from .pycgmKinetics i...
def find_delimiter_loc(delimiter, str): """Return a list of delimiter locations in the str""" out = [] pos = 0 while pos < len(str): if str[pos] == "%": out.append(pos) pos += 1 return out
def build_path(pattern, keys): """Replace placeholders in `pattern` to build path to be scraped. `pattern` will be a string like "measure/%(measure)s/ccg/%(entity_code)s/". """ substitutions = { "practice_code": "L83100", "ccg_code": "15N", "stp_code": "E54000037", "reg...
def scramble(mouvs): """ Converts movements from boolean and str to human comprehensive Parameters ---------- mouvs: list The list of movements (tuple : (f, cw, r180)) Returns ------- mvts: str The movements <F B L R U D> [' 2] [_] """ mvts = "" for mvt in mouvs: # Add LETTER + possibly ' or 2 + SPAC...
def binary_search(arr, left, right, item): """ >>> binary_search([1,2,3,4,5,6], 0, 5, 6) 5 >>> binary_search([2,5], 0, 1, 5) 1 >>> binary_search([0], 0, 0, 1) -1 """ if right >= left: mid = left + (right - left) // 2 if arr[mid] == item: return mid if arr[mid] > item: return binary_search(arr, le...
def get_feature_code(properties, yearsuffix): """ Get code from GeoJSON feature """ code = None if 'code' in properties: code = properties['code'] elif ('lau1' + yearsuffix + 'cd') in properties: code = properties['lau1' + yearsuffix + 'cd'] return code
def intt(tup): """Returns a tuple components as ints""" return (int(tup[0]),int(tup[1]))
def compute_sum(r: int, g: int, b: int) -> int: """ Author: Zakaria Ismail RETURNS the sum of three numbers PASSED. If sum exceeds 255, then the sum is 255. >> compute_sum(5,6,7) 18 """ if r + g + b <= 255: return r + g + b else: return 255
def decrementAny(tup): """ the closest tuples to tup: decrementing by 1 along any dimension. Never go into negatives though. """ res = [] for i, x in enumerate(tup): if x > 0: res.append(tuple(list(tup[:i]) + [x - 1] + list(tup[i + 1:]))) return res
def find_region(t, dt, dt_buffer=0.0): """ This function creates regions based on point-data. So, given an array t, each point will be assigned a region defined by -dt/+dt. These small regions are all collapsed into larger regions that define full 1d spaces of point data. Example: ...
def ERR_NOSUCHNICK(sender, receipient, message): """ Error Code 401 """ return "ERROR from <" + sender + ">: " + message
def compute_total_matching_score(sem_score_norm, struc_score_norm, cn_score_norm, var_score_norm, a=0.2): """ Computes overall formula features score. It discriminates the contributions between features. Semantic and structural features are more important than constant ...
def humanize_number(x): """Convert number to human readable string.""" abs_x = abs(x) if abs_x > 1e6: return f"{x/1e6:.0f}m" elif abs_x > 1e3: return f"{x/1e3:.0f}k" elif abs_x > 10: return f"{x:.0f}" else: return f"{x:.3f}"
def join_path_segments(*args): """Join multiple list of path segments This function is not encoding aware, it does not test for, or changed the encoding of the path segments it's passed. Example:: >>> assert join_path_segments(['a'], ['b']) == ['a','b'] >>> assert join_path_segments(['...
def _convert_dict_to_maestro_params(samples): """Convert a scisample dictionary to a maestro dictionary""" keys = list(samples[0].keys()) parameters = {} for key in keys: parameters[key] = {} parameters[key]["label"] = str(key) + ".%%" values = [sample[key] for sample in samples]...
def timeFormat(time): """Summary Args: time (TYPE): Description Returns: TYPE: Description """ time = int(time) seconds = time%60 time = time//60 minutes = (time)%60 time = time//60 hours = time%60 timeStr = str(hours) +"h " + str(minutes) + "m " + ...
def cubic_ease_in_out(p): """Modeled after the piecewise cubic y = (1/2)((2x)^3) ; [0, 0.5) y = (1/2)((2x-2)^3 + 2) ; [0.5, 1] """ if p < 0.5: return 4 * p * p * p else: f = (2 * p) - 2 return (0.5 * f * f * f) + 1
def _tail(text, n): """Returns the last n lines in text, or all of text if too few lines.""" return "\n".join(text.splitlines()[-n:])
def label_data(dictionary, images): """ Labels the data depending on patient's diagnosis Parameters ---------- dictionary: Dict with patient information images: Names of images to label Returns ------- Labeled data """ data = [] last_patient = '' aux = [] for img...
def onlyHive(fullData): """ Parses the fullData set and returns only those servers with "hive" in their name. This could probably be generalized to return other machines like those in Soda. """ toReturn = {} for server in fullData: if str(server)[0:4] == "hive": toRet...
def short_kill_x(well, neighbor): """If the well is melanophore and neighbor is xantophore, kill the melanophore""" # Note that original paper assumes that the chromaphores kill each other at the same rate (sm == sx == s) if (well == 'M') & (neighbor == 'X'): return 'S' else: return well
def update(m, k, f, *args, **kwargs): """clojure.core/update for Python's stateful maps.""" if k in m: m[k] = f(m[k], *args, **kwargs) return m
def r_sum(nested_num_list): """ (list) -> float Sum up the values in a nested numbers list """ cntr = 0 for elem in nested_num_list: # Traverse the list # Recursive call for nested lists if isinstance(elem, list): cntr += r_sum(elem) # Base case ...
def migrate_stream_data(page_or_revision, block_path, stream_data, mapper): """ Recursively run the mapper on fields of block_type in stream_data """ migrated = False if isinstance(block_path, str): block_path = [block_path, ] if len(block_path) == 0: return stream_data, False # S...
def get_qrels(iterable): """ Get annotated weights for iunits """ qrels = {} for line in iterable: qid, uid, weight = line.rstrip().split('\t', 2) qrels[(qid, uid)] = weight return qrels
def format_image_expectation(profile): """formats a profile image to match what will be in JSON""" image_fields = ['image', 'image_medium', 'image_small'] for field in image_fields: if field in profile: profile[field] = "http://testserver{}".format(profile[field]) return profile
def html_encode(text): """ Encode ``&``, ``<`` and ``>`` entities in ``text`` that will be used in or as HTML. """ return (text.replace('&', '&amp;').replace('<', '&lt;'). replace('>', '&gt;'))
def make_special_ticks(arr): """Makes x axis tick labels for `plot_time_errors` by iterating through a given array Args: arr (iterable): The elements which will end up in the axis tick labels. Returns: list: the axis tick labels """ s = "$t={} \\ \\to \\ t={}$" return [s....
def invert_filters(reference_filters): """Inverts reference query filters for a faster look-up time downstream.""" inverted_filters = {} for key, value in reference_filters.items(): try: # From {"cats_ok": {"url_key": "pets_cat", "value": 1, "attr": "cats are ok - purrr"},} #...
def XYZ_to_uv76(X, Y, Z): """ convert XYZ to CIE1976 u'v' coordinates :param X: X value :param Y: Y value (luminance) :param Z: Z value :return: u', v' in CIE1976 """ denominator = (X + (15 * Y) + (3 * Z)) if denominator == 0.0: u76, v76 = 0.0, 0.0 else: u76 = (4 * X...
def inverse_quadratic_rbf(r, kappa): """ Computes the Inverse-Quadratic Radial Basis Function between two points with distance `r`. Parameters ---------- r : float Distance between point `x1` and `x2`. kappa : float Shape parameter. Returns ------- phi ...
def pad_seq_with_mask(seq, mask): """Given a shorter sequence, expands it to match the padding in mask. Args: seq: String with length smaller than mask. mask: String of '+'s and '-'s used to expand seq. Returns: New string of seq but with added '-'s where indicated by mask. """...
def is_simple(word): """Decide if a word is simple.""" return len(word) < 7
def total_capacity(facilities: list) -> int: """ Function to obtain the total capacity of all facilities of the current problem :param facilities: list of problem instance's facilities :return: an int representing the total capacity of all the facilities """ tot_capacity = 0 for f...
def get_file_index(file: str) -> int: """Returns the index of the image""" return int(file.split('_')[-1].split('.')[0])
def github_html_url_to_api(url): """ Convert https://github.com links to https://api.gitub.com """ if url.startswith('https://github.com/'): return "https://api.github.com/repos/" + url[19:] else: return None
def convert_to_valid_int(value): """ Purpose: Converts a string to an int. Args: value - string/float Returns: value - of type int. """ return int(float(value))
def update_signatures(signatures, v): """Updates the signature dictionary. Args: signatures (dict): Signature dictionary, which can be empty. v (dict): A dictionary, where the keys are: mime: the file mime type signs: a list of comma separated strings containing the ...
def __get_years_tickvals(years): """ Helper function to determine the year ticks for a graph based on how many years are passed as input Parameters ---------- years : list A list of the years for this dataset Returns ------- year_ticks : list A list of places fo...
def test_alnum(arr): """ Returns false if list contains non-alphanumeric strings """ for element in arr: if not element.isalnum(): return False return True
def alphadump(d, indent=2, depth=0): """Dump a dict to a str, with keys in alphabetical order. """ sep = "\n" + " " * depth * indent return "".join( ( "{}: {}{}".format( k, alphadump(d[k], depth=depth + 1) if isinstance(d[k], dict) ...
def problem_2_1(node): """ Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed? """ # This algorithm solves the harder follow-up problem. start = node while node != None: succ = node.next ...
def toUpperCamelCase(text): """converts a given Text to a upper camel case text this is a example -> ThisIsAExample""" splittedText = text.split() upperCamelCase = '' for t in splittedText: upperCamelCase += t[0:1].capitalize() upperCamelCase += t[1:] return upperCamelCase
def loadstastic(file): """ this method takes an ALREADY SCRUBBED chunk of file(string), and convert that into a WordLists (see :return for this function or see the document for 'test' function, :param WordLists) :param file: a string contain an AlREADY SCRUBBED file :return: a WordLists: Array type...
def hgt_to_mb(hgt, mslp=1013.25): """Convert altitude, in meters, to expected millibars.""" return mslp*(1-hgt/44307.69396)**5.2553026