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 the supplier application - Note array is prefixed with the DM supplier ID :param questions: :return array of strings representing headers: """ csv_headers = list() csv_headers.append('Digital Marketplace ID') csv_headers.append('Digital Marketplace Name') csv_headers.append('Digital Marketplace Duns number') csv_headers.append('State of Declaration') for index, value in enumerate(questions): csv_headers.append("{}:{}".format(index+1, value)) return csv_headers
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 result = [] for i in range(1, n + 1): numerator = prev_numerator + 2 * prev_denominator denominator = prev_numerator + prev_denominator if len(str(numerator)) > len(str(denominator)): result.append(i) prev_numerator = numerator prev_denominator = denominator return len(result)
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 as value for each key """ dikt = {} for i in lst: dikt[i] = payload return dikt
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 bits return min(bits, (~number & (number - 1)).bit_length())
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[token_seq].items(), key=lambda k: k[1])[0] return max_successor
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 the rules directory with that name. When nursery rules are loaded, their metadata section should be updated with: `nursery=True`. """ return "nursery" in path
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 in partition)
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.items()}
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 the updated values :type new: dict :return: Updated dictionary :rtype: dict """ for key, new_value in new.items(): old_value = old.get(key) if (isinstance(old_value, dict) and isinstance(new_value, dict)): old[key] = update_nested_dictionary(old_value, new_value) else: old[key] = new_value return old
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 indicating which ROM address offsets to write and what to write to them """ return [{'1573402': [0 if music else 1]}]
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_raw_base_qual() offset : int The offset to add to the quality values when converting to ASCII Returns ------- str The ASCII encoded SAM representation of the quality scores """ return "".join([chr(q + offset) for q in list(raw_base_qual)])
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 recent call last): ... TypeError: zip argument #1 must support iteration >>> transpose([[1,2,3]]) [[1], [2], [3]] >>> transpose( [[2, 2, 2], [2, 2, 2]] ) [[2, 2], [2, 2], [2, 2]] >>> transpose( [(2, 2, 2), (2, 2, 2)] ) [(2, 2), (2, 2), (2, 2)] >>> transpose( ([2, 2, 2], [2, 2, 2]) ) ([2, 2], [2, 2], [2, 2]) >>> transpose( ((2, 2, 2), (2, 2, 2)) ) ((2, 2), (2, 2), (2, 2)) >>> t = [[[1], [2]], [[3], [4]], [[5], [6]]] >>> transpose(t) [[[1], [3], [5]], [[2], [4], [6]]] """ if isinstance(m, list): if isinstance(m[0], list): return map(list, zip(*m)) else: return zip(*m) # faster else: if isinstance(m[0], list): return tuple(map(list, zip(*m))) else: return tuple( zip(*m) )
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 '_*': protectedline.append('\\' + c) else: protectedline.append(c) lines[i][1] = ''.join(protectedline) return lines
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 memory nodes (HP Proliant DL560) c986-c989 new huge memory nodes (Dell R930) TOTAL Haswell 406 """ if node.strip() in ['c'+str(x) for x in range(1, 310)]: return 'SandyBridge' if node.strip() in ['c'+str(x) for x in range(321, 479)]: return 'SandyBridge' if node.strip() in ['c'+str(x) for x in range(579, 629)]: return 'Haswell' if node.strip() in ['c'+str(x) for x in range(639, 986)]: return 'Haswell' if node.strip() in ['c'+str(x) for x in range(309, 321)]: return 'SandyBridgeBig' if node.strip() in ['c'+str(x) for x in range(629, 639)]: return 'HaswellBig' if node.strip() in ['c'+str(x) for x in range(577, 579)]: return 'OldHuge' if node.strip() in ['c'+str(x) for x in range(986, 990)]: return 'NewHuge'
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 D_eye > 6.25: age = 33 elif D_eye <= 6.25 and D_eye > 5.75: age = 40 elif D_eye <= 5.75 and D_eye > 5.25: age = 54 else: age = 70 return age
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_list: targets_dict[target] = (1.0, "foo") return targets_dict
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("_", " ").lower().title()
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 isinstance(format_list, str): attrs = [format_list] return attrs
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_type] = "True" break else: continue return section
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 dictionary before the adjustments :return: dict same dictionary but with the "W" string added to each of the keys """ return {str(key) + "W": value for key, value in parameter_dict.items()}
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_suite): return None # number of outputs != number of test cases result = list() for exe_output, test_case in zip(output_lines, test_suite): # check if exe_output has format "RESULT: <integer>" prefix = "RESULT: " if (not exe_output.startswith(prefix)): return None # the user printed something exe_value = exe_output[len(prefix):] if (test_case['output'] == exe_value): result.append(True) else: result.append(False) return result
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_two[0]: return pow_two[0] if max_sent_tokens >= pow_two[-1]: return pow_two[-1] check = [max_sent_tokens > j for j in pow_two] idx = check.index(False) return pow_two[idx]
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 = token_to_id[answer] story_ids.append((story, query, answer)) return story_ids
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) array = array[:-(array[-1])] return array
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 = op[2] elif op[0] == 1: apos = op[2] elif op[0] == 2: result.append(op[2]) apos = op[1] if apos < len(a): result.append(a[apos:]) # equal return "".join(result)
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(_) for _ in params_list] for iv, value in enumerate(options): if iv > 0 or ip == 0: to_update = [dict(_) for _ in _params_list] params_list += to_update else: to_update = params_list for param_set in to_update: param_set[param] = value return params_list
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 based on structural analysis. :param chord: wing mean chord [m] :param span: wing span [m] :param mean_t_over_c: wing thickness-to-chord ratio [unitless] :return: estimated surface mass [kg] """ mean_t = chord * mean_t_over_c volume = chord * span * mean_t return density * volume
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 # Trick to create a ones mask of n bits x_base = (x << shift) & mask # Keep it in the n_bits range return x_base | (x >> (n_bits - shift))
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(idx): if idx == n: return True # Base case, end of string and all letters matched if string[idx] == string[n-1-idx]: return recurse(idx+1) return False return recurse(0)
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 """ names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] if month_name in names: return names.index(month_name) + 1 else: return 0
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 import vector >>> v = [1,2,3] >>> e = [4,5,6] >>> vector(v, e) (3, 3, 3) >>> v = np.array([5.10897693, 6.18161923, 9.44221215]) >>> e = np.array([3.68040209, 9.92542233, 5.38362424]) >>> vector(v, e) (-1.42857484, 3.7438031, -4.05858791) """ x,y,z = b X,Y,Z = e return (X-x, Y-y, Z-z)
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", "regional_team_code": "Y58", "bnf_code": "0205051R0BBAIAN", "measure": "ace", } path = pattern for key in keys: subst_key = None if key in ["code", "entity_code"]: for token in ["practice", "ccg", "stp", "regional-team"]: if token in pattern: subst_key = "{}_code".format(token).replace("-", "_") if subst_key is None: subst_key = "bnf_code" else: subst_key = key path = path.replace("%({})s".format(key), substitutions[subst_key]) assert "%" not in path, "Could not interpolate " + pattern return path
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 + SPACE mvts += mvt[0] + ("2" if mvt[2] else "" if mvt[1] else "'") + " " return mvts.strip()
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, left, mid - 1, item) return binary_search(arr, mid + 1, right, item) return -1
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: import numpy as np import icesatPlot as ip import region_detect as rd x = np.linspace(0,100) dx = rd.est_dx(x) x_cut, _ = rd.filt_reg_x(x, [[10,20], [30,40], [50,60]]) regions, index = rd.find_region(x_cut, 2*dx) fig, ax = ip.make_fig() ax.plot(x_cut, x_cut, '.') ylim = ax.get_ylim() for reg in regions: ax.plot([reg[0], reg[0]], ylim, 'g--') # start ax.plot([reg[1], reg[1]], ylim, 'r--') # end fig.show() """ degrade = [] degrade_index_red = [] if len(t) > 0: # This works by first giving every outlier point a region defined by # deg_definition_dt. Then, regions are added to degrade_index, and # each overlapping super region is separated from one-another. # Then the first and last points of each super region are used to define # the overall degrade at that set of points. deg_regions = [[t[0] - dt, t[0] + dt]] degrade_index = [[0]] for k in range(1, len(t)): deg_t = t[k] deg_regions.append([deg_t - dt, deg_t + dt]) # deg_start1 = deg_regions[k-1][0] deg_end1 = deg_regions[k-1][1] deg_start2 = deg_regions[k][0] # deg_end2 = deg_regions[k][1] if deg_end1 > deg_start2: # degrade regions overlap degrade_index[-1].append(k) else: degrade_index.append([]) degrade_index[-1].append(k) # degrade_index[d] is a list of k-indices, the degrade regions # that all overlap, or a single region if len(degrade_index[d]) == 1 for d in range(len(degrade_index)): # handles single point or multiple regions that overlap # in single point case, degrade_index[d][0] == degrade_index[d][-1] d_start = deg_regions[degrade_index[d][0]][0] # "deg_start1", or "deg_start1" in single-point case d_end = deg_regions[degrade_index[d][-1]][1] # "deg_end2", or "deg_end1" in single-point case d_start += (dt - dt_buffer) d_end += (-dt + dt_buffer) degrade.append([d_start, d_end]) degrade_index_red.append([degrade_index[d][0], degrade_index[d][-1]]) # fp_outlier_deg_h.write('%d %15.6f %15.6f %15.6f\n' % (i+1, degrade_start, degrade_end, degrade_end - degrade_start)) return degrade, degrade_index_red
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 and variable features and thus given more weights. Args: sem_score_norm: Normalized semantic matching score. struc_score_norm: Normalized structural matching score. cn_score_norm: Normalized constant matching score. var_score_norm: Normalized variable matching score. a: weight the contribution between features. Returns: The total formula matching score. """ return ((1 - a) * (sem_score_norm + struc_score_norm) + a * (cn_score_norm + var_score_norm)) / float(2)
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(['a',''], ['b']) == ['a','b'] >>> assert join_path_segments(['a'], ['','b']) == ['a','b'] >>> assert join_path_segments(['a',''], ['','b']) == ['a','','b'] >>> assert join_path_segments(['a','b'], ['c','d']) == ['a','b','c','d'] :param args: optional arguments :return: :class:`list`, the segment list of the result path """ finals = [] for segments in args: if not segments or segments[0] == ['']: continue elif not finals: finals.extend(segments) else: # Example #1: ['a',''] + ['b'] == ['a','b'] # Example #2: ['a',''] + ['','b'] == ['a','','b'] if finals[-1] == '' and (segments[0] != '' or len(segments) > 1): finals.pop(-1) # Example: ['a'] + ['','b'] == ['a','b'] elif finals[-1] != '' and segments[0] == '' and len(segments) > 1: segments.pop(0) finals.extend(segments) return finals
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] parameters[key]["values"] = values return parameters
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 " + str(seconds) + "s" return(timeStr)
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 in images: patientid = img[5:15] if last_patient == '': last_patient = patientid aux.append(img) continue if patientid == last_patient: aux.append(img) else: last_date = aux[-1][16:22] if last_patient + last_date in dictionary: dx = dictionary[last_patient + last_date] for a in aux: data.append((a, dx)) aux = [img] last_patient = patientid return data
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": toReturn[server] = fullData[server] return toReturn
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 elif isinstance(elem, (int, float)): cntr += elem else: raise TypeError('Invalid value found in list: {0}'.format(elem)) return cntr
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 # Separate out the current block name from its child paths block_name = block_path[0] child_block_path = block_path[1:] for field in stream_data: if field['type'] == block_name: if len(child_block_path) == 0: value = mapper(page_or_revision, field['value']) field_migrated = True else: value, field_migrated = migrate_stream_data( page_or_revision, child_block_path, field['value'], mapper ) if field_migrated: field['value'] = value migrated = True return stream_data, migrated
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.format(i, i+1) for i in arr]
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"},} # To {"cats are ok - purrr": {"cats_ok": "true"},} inverted_filters[value["attr"]] = {key: "true"} except KeyError: # For filters with multiple values. # From {'auto_bodytype': ['bus', 'convertible', ... ],} # To {'bus': 'auto_bodytype', 'convertible': 'auto_bodytype', ... ,} if isinstance(value, dict): inverted_filters.update({child_value: key for child_value in value}) return inverted_filters
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) / denominator v76 = (9 * Y) / denominator return u76, v76 # u', v' in CIE1976
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 : float Radial basis function response. """ return 1. / (1. + (r * kappa) ** 2.)
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. """ seq_iter = iter(seq) new_seq = "" for m in mask: if m == "+": new_seq += next(seq_iter) elif m == "-": new_seq += "-" return new_seq
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 facility in facilities: tot_capacity += facility.capacity return tot_capacity
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 offsets and the hex signatures. Returns: dict: The signature dictionary with signatures from v """ mime = v.get("mime") # signs is a list of file signatures signs = v.get("signs") for sign in signs: # Each signature is a comma separated string # The number before the comma is the offset # The string after the comma is the signature hex. arr = sign.split(",") offset = arr[0] hex = arr[1] # Ignore 00 as it might appear in different files. if hex == "00": continue offset_signatures = signatures.get(offset, {}) offset_signatures[hex] = mime signatures[offset] = offset_signatures return signatures
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 for tick marks on the years axis of the graph """ min_year = int(min(years)) max_year = int(max(years)) delta = max_year - min_year if delta >= 80: stepsize = 10 elif delta >= 40: stepsize = 5 elif delta >= 16: stepsize = 2 else: stepsize = 1 year_ticks = list(range(min_year, max_year + stepsize, stepsize)) return year_ticks
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) else str(d[k]), sep, ) for k in sorted(d.keys()) ) )
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 while succ != None and succ.key == node.key: succ = succ.next node.next = succ node = succ return start
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 each element of array represent a chunk, and it is a dictionary type each element in the dictionary maps word inside that chunk to its frequency """ Words = file.split() Wordlist = {} for word in Words: try: Wordlist[word] += 1 except: Wordlist.update({word: 1}) return Wordlist
def hgt_to_mb(hgt, mslp=1013.25): """Convert altitude, in meters, to expected millibars.""" return mslp*(1-hgt/44307.69396)**5.2553026