content
stringlengths
42
6.51k
def makemarkers(nb): """ Give a list of cycling markers. See http://matplotlib.org/api/markers_api.html .. note:: This what I consider the *optimal* sequence of markers, they are clearly differentiable one from another and all are pretty. Examples: >>> makemarkers(7) ['o', 'D', 'v', 'p', '<', 's', '^'] >>> makemarkers(12) ['o', 'D', 'v', 'p', '<', 's', '^', '*', 'h', '>', 'o', 'D'] """ allmarkers = ['o', 'D', 'v', 'p', '<', 's', '^', '*', 'h', '>'] longlist = allmarkers * (1 + int(nb / float(len(allmarkers)))) # Cycle the good number of time return longlist[:nb]
def is_chinese_char(cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean # characters, despite its name. The modern Korean Hangul alphabet is a # different block, as is Japanese Hiragana and Katakana. Those alphabets # are used to write space-separated words, so they are not treated # specially and handled like the all of the other languages. return (0x4E00 <= cp <= 0x9FFF) or \ (0x3400 <= cp <= 0x4DBF) or \ (0x20000 <= cp <= 0x2A6DF) or \ (0x2A700 <= cp <= 0x2B73F) or \ (0x2B740 <= cp <= 0x2B81F) or \ (0x2B820 <= cp <= 0x2CEAF) or \ (0xF900 <= cp <= 0xFAFF) or \ (0x2F800 <= cp <= 0x2FA1F)
def calculate(x: int, y: int = 1, *, subtract: bool = False) -> int: """Calculate sum (or difference) of two numbers. Parameters: `x` : int, required The first number `y` : int, optional The second number (default is 1) `subtraction`: bool, optional Whether to perform subtraction. Default is False. Returns: int The result of the operation on `x` and `y` """ return x - y if subtract else x + y
def paths_that_contain(paths, nodes, bool_and=False): """Return paths that contain at least one or all of the nodes. Parameters ---------- paths : list. list of paths where each path is a tuple of integers. Example : [(1,2,3), (1,3,4)] nodes : list. List of nodes that the paths are going to be searched for. bool_and : bool. If True, the sufficient requirement is that all nodes are in a path. If False, the sufficient requirement is that at least one of the nodes is in a path. Returns ------- paths_ : list. list of paths that contain at least one or all of the nodes in 'nodes'. """ paths_ = [] # Must contain all nodes. if bool_and: for path in paths: contains = True for node in nodes: if node in path: continue else: contains = False break # If no breaks happen, all nodes are in path. (Sufficient requirement.) if contains: paths_.append(path) # Must contain at least one of the nodes. elif not bool_and: for path in paths: for node in nodes: if node in path: paths_.append(path) break return paths_
def make_scp_safe(string: str) -> str: """ Helper function to make a string safe for saving in Kaldi scp files. They use space as a delimiter, so any spaces in the string will be converted to "_MFASPACE_" to preserve them Parameters ---------- string: str Text to escape Returns ------- str Escaped text """ return string.replace(" ", "_MFASPACE_")
def make_img(file, width, height): """ :param file: :param width: :param height: :return: """ return { 'type': 'image', 'file': file, 'width': width, 'height': height }
def bbox(coords1, coords2): """ Create BBox between two coordinates :param coords1: coords1 Point coordinate :param coords2: coords2 Point coordinate :return: Bounding Box as [west, south, east, north] """ x1 = coords1[0] y1 = coords1[1] x2 = coords2[0] y2 = coords2[1] if x1 < x2: west = x1 else: west = x2 if y1 < y2: south = y1 else: south = y2 if x1 > x2: east = x1 else: east = x2 if y1 > y2: north = y1 else: north = y2 return [west, south, east, north]
def regionFromResize(curr_width, curr_height, bounds_width, bounds_height): """Region from Resize Returns a new set of region points based on a current width and height and the bounding box Args: curr_width (uint): The current width curr_height (uint): The current height bounds_width (uint): The boundary width bounds_height (uint): The boundary height Returns: list [x, y, width, height] """ # Return lRet = [0, 0, 0, 0] # If the current width is larger than the bounds width if curr_width > bounds_width: lRet[0] = int(round((curr_width - bounds_width) / 2.0)) lRet[1] = 0 lRet[2] = int(bounds_width + round((curr_width - bounds_width) / 2.0)) lRet[3] = bounds_height # Else if the current height is larger than the bounds height else: lRet[0] = 0 lRet[1] = int(round((curr_height - bounds_height) / 2.0)) lRet[2] = bounds_width lRet[3] = int(bounds_height + round((curr_height - bounds_height) / 2.0)) # Return the region return lRet
def np_within(x, target, bounds): """Is x within within bounds (positive or negative) of expected""" return (x - target) ** 2 < bounds ** 2
def build_json_response(status, value): """ Generate json format from input params :param status: string :param value: string :return: json array """ return { 'status': status, 'message': value }
def bezier(t, x1, y1, x2, y2): """The famous Bezier curve.""" m = 1 - t p = 3 * m * t b, c, d = p * m, p * t, t * t * t return (b * x1 + c * x2 + d, b * y1 + c * y2 + d)
def final_strategy(score, opponent_score): """Write a brief description of your final strategy. *** YOUR DESCRIPTION HERE *** """ # BEGIN PROBLEM 12 "*** REPLACE THIS LINE ***" "" return 4 # END PROBLEM 12
def seq3(seq): """Turn a one letter code protein sequence into one with three letter codes. The single input argument 'seq' should be a protein sequence using single letter codes, either as a python string or as a Seq or MutableSeq object. This function returns the amino acid sequence as a string using the three letter amino acid codes. Output follows the IUPAC standard (including ambiguous characters B for "Asx", J for "Xle" and X for "Xaa", and also U for "Sel" and O for "Pyl") plus "Ter" for a terminator given as an asterisk. Any unknown character (including possible gap characters), is changed into 'Xaa'. e.g. >>> from Bio.SeqUtils import seq3 >>> seq3("MAIVMGRWKGAR*") 'MetAlaIleValMetGlyArgTrpLysGlyAlaArgTer' This function was inspired by BioPerl's seq3. """ threecode = {'A':'Ala', 'B':'Asx', 'C':'Cys', 'D':'Asp', 'E':'Glu', 'F':'Phe', 'G':'Gly', 'H':'His', 'I':'Ile', 'K':'Lys', 'L':'Leu', 'M':'Met', 'N':'Asn', 'P':'Pro', 'Q':'Gln', 'R':'Arg', 'S':'Ser', 'T':'Thr', 'V':'Val', 'W':'Trp', 'Y':'Tyr', 'Z':'Glx', 'X':'Xaa', '*':'Ter', 'U':'Sel', 'O':'Pyl', 'J':'Xle', } #We use a default of 'Xaa' for undefined letters #Note this will map '-' to 'Xaa' which may be undesirable! return ''.join([threecode.get(aa,'Xaa') for aa in seq])
def extract_type(tag: str, sep: str = "-") -> str: """Extract the span type from a tag. Tags are made of two parts. The second part is the type of the span which is specific to the downstream task. This function extracts that value from the tag. Args: tag: The tag to extract the type from. sep: The character (or string of characters) that separate the token function from the span type. Returns: The span type. """ if sep not in tag: return tag return tag.split(sep, maxsplit=1)[1]
def intersect(box1, box2): """Calculate the intersection of two boxes.""" b1_x0, b1_y0, b1_x1, b1_y1 = box1 b2_x0, b2_y0, b2_x1, b2_y1 = box2 x0 = max(b1_x0, b2_x0) y0 = max(b1_y0, b2_y0) x1 = min(b1_x1, b2_x1) y1 = min(b1_y1, b2_y1) if x0 > x1 or y0 > y1: # No intersection, return None return None return (x0, y0, x1, y1)
def depth(obj): """ """ if obj == []: return 1 elif isinstance(obj, list): return 1 + max([depth(x) for x in obj]) else: return 0
def compare_matches(matches, target) -> bool: """ Make sure the matches and target matches are the same. """ for match in target: if match not in matches and tuple(reversed(match)) not in matches: return False return True
def predictor_fail(body): """ Callback function which work when properties prediction failed :param body: MassTransit message """ global PREDICTOR_FAIL_FLAG PREDICTOR_FAIL_FLAG = True return None
def _BackendPremultiplication(color): """Apply premultiplication and unpremultiplication to match production. Args: color: color tuple as returned by _ArgbToRgbaTuple. Returns: RGBA tuple. """ alpha = color[3] rgb = color[0:3] multiplied = [(x * (alpha + 1)) >> 8 for x in rgb] if alpha: alpha_inverse = 0xffffff / alpha unmultiplied = [(x * alpha_inverse) >> 16 for x in multiplied] else: unmultiplied = [0] * 3 return tuple(unmultiplied + [alpha])
def normal_mapping(time, tex_coords, viewer_dir, unit_normal, tangent_t, tangent_b, *args, **kw): """ dummy """ normal_map = kw.get('normal_map', 'none') unit_new_normal = unit_normal return (unit_new_normal, tex_coords)
def parse_resume_step_from_filename(filename): """ Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the checkpoint's number of steps. """ split = filename.split("model") if len(split) < 2: return 0 split1 = split[-1].split(".")[0] try: return int(split1) except ValueError: return 0
def myreadlines(self): """Read and return the list of all logical lines using readline.""" lines = [] while True: line = self.readline() if not line: return lines else: lines.append(line)
def s_to_x (s, chars): """Convert a string to a list of integers. s_to_x(s, chars) -> x s: string to convert. chars: a list of characters that s may contain, without repetitions. x: a list of integers corresponding to the characters of s by taking the index of the character in chars. """ char_to_digit = dict((c, i) for i, c in enumerate(chars)) return [char_to_digit[c] for c in s]
def compute_jaccard_similarity(query, document): """ function taken explicitly from: http://billchambers.me/tutorials/2014/12/21/tf-idf-explained-in-python.html calculates the intersection over union of a query in a given document. """ intersection = set(query).intersection(set(document)) union = set(query).union(set(document)) return len(intersection)/len(union)
def find_duplicates(boreField, disp=False): """ The distance method :func:`Borehole.distance` is utilized to find all duplicate boreholes in a boreField. This function considers a duplicate to be any pair of points that fall within each others radius. The lower index (i) is always stored in the 0 position of the tuple, while the higher index (j) is stored in the 1 position. Parameters ---------- boreField : list A list of :class:`Borehole` objects disp : bool, optional Set to true to print progression messages. Default is False. Returns ------- duplicate_pairs : list A list of tuples where the tuples are pairs of duplicates """ duplicate_pairs = [] # define an empty list to be appended to for i in range(len(boreField)): borehole_1 = boreField[i] for j in range(i, len(boreField)): # only loop unique interactions borehole_2 = boreField[j] if i == j: # skip the borehole itself continue else: dist = borehole_1.distance(borehole_2) if abs(dist - borehole_1.r_b) < borehole_1.r_b: duplicate_pairs.append((i, j)) if disp: print(' gt.boreholes.find_duplicates() '.center(50, '-')) print('The duplicate pairs of boreholes found: {}'\ .format(duplicate_pairs)) return duplicate_pairs
def rotate(matrix): """ :contrarotate matrix. """ return list(map(list,zip(*matrix[::])))[::-1]
def get_title(html): """Finds a title in a HTML document.""" title_tag = '<title>' start = html.find(title_tag) if start < 0: return None end = html.find('</title>', start) if end < 0: return None return html[start + len(title_tag): end]
def or_field_filters(field_name, field_values): """OR filter returns documents that contain a field matching any of the values. Returns a list containing a single Elasticsearch "terms" filter. "terms" filter matches the given field with any of the values. "bool" execution generates a term filter (which is cached) for each term, and wraps those in a bool filter. This way each individual value match is cached (as opposed to the default of caching the whole filter result) and the cache can be reused in different combinations of values. (https://www.elastic.co/guide/en/elasticsearch/reference/1.6/query-dsl-terms-filter.html) """ return [ { "terms": { field_name: field_values[0].split(","), }, }, ]
def fib(num): """ Check if a number is in the Fibonacci sequence. :type num: integer :param num: The number to check. >>> fib(8) True >>> fib(4) False """ num1 = 1 num2 = 1 while True: if num2 < num: tempnum = num2 num2 += num1 num1 = tempnum else: return num2 == num
def clip_point(p,size): """ Ensure 0 <= p < size. Parameters ---------- p : int Point to clip. size : int Size of the image the point sits in. Returns ------- p : int Clipped point. """ return min(max(0,p),size);
def create_numeric_suffix(base, count, zeros): """Create a string based on count and number of zeros decided by zeros :param base: the basename for new map :param count: a number :param zeros: a string containing the expected number, coming from suffix option like "%05" """ spli = zeros.split('%') if len(spli) == 2: suff = spli[1] if suff.isdigit(): if int(suff[0]) == 0: zero = suff else: zero = "0{nu}".format(nu=suff) else: zero = '05' else: zero = '05' s = '{ba}_{i:' + zero + 'd}' return s.format(ba=base, i=count)
def predict(row, weights): """ Super simple one layer perceptron based on this example: https://machinelearningmastery.com/ implement-perceptron-algorithm-scratch-python/ """ activation = weights[0] for i in range(len(row)-1): activation += weights[i + 1] * row[i] if activation >= 0.0: return 1 else: return 0.0
def calc_overlap_extensible(agent_traits, neighbor_traits): """ Given sets, the overlap and probabilities are just Jaccard distances or coefficients, which are easy in python given symmetric differences and unions between set objects. This also accounts for sets of different length, which is crucial in the extensible and semantic models. """ overlap = len(agent_traits.intersection(neighbor_traits)) #log.debug("overlap: %s", overlap) return overlap
def _get_summary_name(tensor, name=None, prefix=None, postfix=None): """Produces the summary name given. Args: tensor: A variable or op `Tensor`. name: The optional name for the summary. prefix: An optional prefix for the summary name. postfix: An optional postfix for the summary name. Returns: a summary name. """ if not name: name = tensor.op.name if prefix: name = prefix + '/' + name if postfix: name = name + '/' + postfix return name
def critical_events_in_outputs(healthcheck_outputs): """Given a list of HealthCheckResults return those which are unhealthy. """ return [healthcheck for healthcheck in healthcheck_outputs if healthcheck.healthy is False]
def kind(n, ranks): """ Return the first rank that this hand has exactly n of. Return None if there is no n-of-a-kind in the hand. Args: n: number of equal ranks to be checked. Valid values: 1 to 4. ranks: list of ranks of cards in descending order. """ for r in ranks: if ranks.count(r) == n: return r return None
def unique(l): """ Create a new list from l with duplicate entries removed, while preserving the original order. """ new_list = [] for el in l: if el not in new_list: new_list.append(el) return new_list
def calculate(start_a): """ >>> calculate(0) 1848 >>> calculate(1) 22157688 """ a = 0 b = 10551260 if start_a == 1 else 860 for d in range(1, b + 1): if b % d == 0: a += d return a
def transform_in_list(list_in, list_type=None): """Transform a 'String or List' in List""" if list_in is None: list_in = '' if not list_in == list(list_in): list_in = list_in.split() if list_type: print(list_type, list_in) return list_in
def behzad(x,y): """this is just a DocString""" z=x**2+y**2 return z
def duplicate_encode(word): """This function is the solution to the Codewars Duplicate Encoder Kata that can be found at: https://www.codewars.com/kata/54b42f9314d9229fd6000d9c/train/python.""" word_lowercase = word.lower() occurrences = {} for character in list(word_lowercase): number_of_times = occurrences.get(character, 0) number_of_times += 1 occurrences[character] = number_of_times encoded_string = [] for character in word_lowercase: if occurrences[character] == 1: encoded_string.append('(') else: encoded_string.append(')') return ''.join(encoded_string)
def extract_code(number): """extract area code from number. Args: number: number to analyze Returns: area code """ if number[0] == '(': first_bracket = number.find('(') + 1 second_bracket = number.find(')') return number[first_bracket:second_bracket] elif number[0:3] != '140': return number[0:4] else: return 140
def sizeof_fmt(num, suffix='B'): """Format bytes into human friendly units.""" for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def get_tag_options(label_matches): """Returns a list of the unique tags present in label_matches.""" tag_options = [] for key in label_matches.keys(): if key[1] not in tag_options: tag_options.append(key[1]) return tag_options
def version(val): """Calculate a string version from an integer value.""" ver = val / 100. if val > 2. * 100. else val / 10. return f'{ver:.1f}'
def pairwise_disjoint(c): """Return whether elements in `c` are pairwise disjoint.""" union = set().union(*c) n = sum(len(u) for u in c) return n == len(union)
def calc_k_neg1(T_K): """ Calculates k1- kinetic constant from Table 1 of Kaufmann and Dreybrodt (2007). Parameters ---------- T_K : float temperature Kelvin Returns ------- k_neg1 : float kinetic constant k1- Notes ----- Related to the rate of CO2 conversion. """ k_neg1 = 10.**(13.558 - 3617.1/T_K) return k_neg1
def normalize(x: int) -> int: """Normalize an integer between -1 and 1.""" if x > 0: return 1 elif x < 0: return -1 return 0
def parse_results(results): """Break up multiline output from ls into a list of (name, size) tuples.""" return [(line.split()[8], int(line.split()[4])) for line in results.splitlines() if line.strip()] #return [(line.split()[1], int(line.split()[0])) for line in results.splitlines() if line.strip()]
def apply_iam_bindings_patch(current_policy, bindings_patch, action): """ Patches the current policy with the supplied patch. action can be add or remove. """ for item in bindings_patch['bindings']: members = item['members'] roles = item['roles'] for role in roles: if role not in current_policy.keys(): current_policy[role] = set() if action == "add": current_policy[role].update(members) else: current_policy[role].difference_update(members) return current_policy
def get_module_url(module_items_url): """ Extracts the module direct url from the items_url. Example: items_url https://canvas.instance.com/api/v1/courses/course_id/modules/module_id/items' becomes https://canvas.instance.com/courses/course_id/modules/module_id """ return module_items_url.replace('api/v1/','').replace('/items', '')
def add_splitter(splits, splitter): """ Adds a spliter back to the splits eg: if splitted on space ' ' ['this', 'is', 'me'] becomes ['this', ' ', 'is', ' ', 'me'] """ restruct = [] no = -1 for x in splits: no += 1 if no == len(splits) - 1: restruct.append(x) break restruct.append(x) restruct.append(splitter) return restruct
def dfs_iter(graph: dict, target, start=None) -> bool: """Iterative DFS. Args: graph: keys are vertices, values are lists of adjacent vertices target: node value to search for start: node to start search from Examples: >>> dfs_iter(graph, 7) True >>> dfs_iter(graph, 8) False Returns: True if `target` found. Otherwise, False. """ if not graph or target not in graph or (start is not None and start not in graph): return False if start is None: start = list(graph.keys())[0] stack = [start] visited = [] while stack: v = stack.pop() if v == target: return True if v not in visited: visited.append(v) for adj in graph[v]: stack.append(adj) return False
def relative_error(value, value_ref): """Return the relative error :param value: [int,float] Value to compare :param value: [int,float] Reference value :return err: float Relative error. """ return (value-value_ref)/value_ref
def var_char(_x=0): """Creats a string version of VARCHAR function Arguments: x {integer} -- [description] Returns: string -- [description] """ return "VARCHAR(" + str(_x) + ")"
def small_caps(text: str) -> str: """ Return the *text* surrounded by the CSS style to use small capitals. Small-caps glyphs typically use the form of uppercase letters but are reduced to the size of lowercase letters. >>> small_caps("Dupont") "<span style='font-variant:small-caps'>Dupont</span>" """ return f"<span style='font-variant:small-caps'>{text}</span>"
def calculate_building_intersection_matrix(bn, nf): """ :param bn: number of buildings (including both sides of the road) :param nf: number of floors in each building :return: number of buildings that lies between any two nodes """ total_nodes = bn * nf node_eachside = int(total_nodes/2) int_mat = [[0 for col in range(total_nodes)] for row in range(total_nodes)] i = 0 while i < node_eachside: j = i + 1 while j < node_eachside: snode = i dnode = j s_id = int(snode / nf) d_id = int(dnode / nf) val = d_id - s_id - 1 if val < 0: val = 0 int_mat[i][j] = val j += 1 i += 1 for i in range(0, node_eachside): for j in range(node_eachside, total_nodes): int_mat[i][j] = 0 for i in range(node_eachside, total_nodes): for j in range(0, node_eachside): int_mat[i][j] = 0 for i in range(0, node_eachside): for j in range(0, node_eachside): if (i != j): int_mat[j][i] = int_mat[i][j] i = total_nodes-1 while i >= node_eachside: j = total_nodes - 1 while j >= node_eachside: int_mat[i][j] = int_mat[total_nodes -1 -i][total_nodes - 1 - j] j = j - 1 i = i - 1 for i in range(node_eachside, total_nodes): for j in range(node_eachside, total_nodes): if (i != j): int_mat[i][j] = int_mat[j][i] return int_mat
def play_or_pass(card_values, pegging_total): """ Determine if the next player has cards to play or should pass. """ action = 'pass' remainder = 31 - pegging_total if any(int(value) <= remainder for value in card_values): action = 'play' return action
def inverse_square(array): """return the inverse square of array, for all elements""" return 1/(array**2)
def is_row_has_tokens_to_remove(tokens, tokens_to_remove: set): """Check if given tokens has no intersection with unnecessary tokens.""" if tokens_to_remove.intersection(set(tokens)): return True return False
def start_vowel(word): """Checks if word starts with a vowel. Returns True if so""" return word[0].lower() in ['a', 'e', 'i', 'o', 'u']
def time_calc(ttime): """Calculate time elapsed in (hours, mins, secs) :param float ttime: Amount of time elapsed :return: int, int, float """ # create local copy tt = ttime # if not divisible by 60 (minutes), check for hours, mins, secs if divmod(tt, 60)[0] >= 1: h_t = divmod(tt, 60 * 60)[0] tt = tt - (h_t * 60 * 60) m_t = divmod(tt, 60)[0] tt = tt - (m_t * 60) s_t = tt return h_t, m_t, s_t # only return seconds else: h_t = 0 m_t = 0 s_t = tt return h_t, m_t, s_t
def stereo_to_mono(data_in): """ byte[] output = new byte[input.Length / 2]; int outputIndex = 0; for (int n = 0; n < input.Length; n+=4) { // copy in the first 16 bit sample output[outputIndex++] = input[n]; output[outputIndex++] = input[n+1]; } """ output = bytearray() for n in range(len(data_in)): if n % 4 == 0: output.append(data_in[n]) output.append(data_in[n + 1]) return bytes(output)
def build_composite_expr(query_values, entity_name, year): """Builds a composite expression with ANDs in OR to be used as MAG query. Args: query_values (:obj:`list` of str): Phrases to query MAG with. entity_name (str): MAG attribute that will be used in query. year (int): We collect data in the [year, now] timeframe. Returns: (str) MAG expression. """ query_prefix_format = "expr=OR({})" and_queries = [ "".join([f"And(Composite({entity_name}='{query_value}'), Y>={year})"]) for query_value in query_values ] return query_prefix_format.format(", ".join(and_queries))
def almul(x, y): """ Function to multiply 2 operands """ return(x * y)
def nice_size(size): """ Returns a readably formatted string with the size >>> nice_size(100) '100 bytes' >>> nice_size(10000) '9.8 KB' >>> nice_size(1000000) '976.6 KB' >>> nice_size(100000000) '95.4 MB' """ words = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'] prefix = '' try: size = float(size) if size < 0: size = abs(size) prefix = '-' except Exception: return '??? bytes' for ind, word in enumerate(words): step = 1024 ** (ind + 1) if step > size: size = size / float(1024 ** ind) if word == 'bytes': # No decimals for bytes return "%s%d bytes" % (prefix, size) return "%s%.1f %s" % (prefix, size, word) return '??? bytes'
def russian_peas(num1, num2): """ We're trying to implement AES polynomial using bit strings. There are two params, and one return value. The AES Irreducible is: P(x) = x8 + x4 + x3 + x + 1 Which should be 0x11A in Hex So if the number multiplied together is larger than 0xFF we need to mod by 0x11A """ # If the num1 == 1, then we're at the point where we need to add # up all the remaining numbers, return up the stack. if num1 == 0x1: return num2 newNum1 = num1 // 0x2 newNum2 = num2 * 0x2 if num1 % 0x2 == 0x0: return russian_peas(newNum1, newNum2) ^ 0x0 else: return russian_peas(newNum1, newNum2) ^ num2
def generate_linear_peptides(pdb_seq): """ Assembling all the linear Pepscan peptides into the protein sequence. parameter: The PDB sequence. Returns: A list containing all the looped peptides. """ step = 5 peptide_mer = 20 linear_list = [] for i in range(0, len(pdb_seq), step): peptide = pdb_seq[i:i + peptide_mer] if len(peptide) is 20: linear_list.append(peptide) return linear_list
def extract_section(soup, attrs={}, name='div', all=False): """ gets the bs4.element.Tag (or list thereof) of a section specified by the attrs (dict or list of dicts) and extracts (rips out of the tree (soup)) the found tags as well (to save memory) """ if soup: # soup is non-None if all==False: if isinstance(attrs,dict): t = soup.find(name=name, attrs=attrs) if t: t.extract() return t else: t = soup for ss in attrs: t = t.find(name=name, attrs=ss) if t: t.extract() return t else: if isinstance(attrs,dict): t = soup.findAll(name=name, attrs=attrs) if t: t.extract() return t else: # not sure how to handle this, so I'm forcing exit print("haven't coded this yet") return None else: return None
def minimum(listy): """ Input: A list of numbers Output: The lowest number in the list, iteration. """ mini = 1000000000000 for i in listy: if i < mini: mini = i if len(listy) == 0: return "None" else: return mini
def create_api_part_search(_id, _qty): """ Creates the map containing the pertinent part search parameters. @param _id: Digi-Key part ID. @param _qty: Part quantity. Should probably be more than zero. @return: A map of the parameters. """ ret = {} ret["Keywords"] = _id ret["RecordCount"] = _qty return ret
def startswith_token(s, prefix, separators=None): """Tests if a string is either equal to a given prefix or prefixed by it followed by a separator. """ if separators is None: return s == prefix prefix_len = len(prefix) if s.startswith(prefix): if len(s) == prefix_len: return True if isinstance(separators, str): sep = separators return s.find(sep, prefix_len) >= 0 for sep in separators: if s.find(sep, prefix_len) >= 0: return True return False
def get_script_tag(source): """ Get HTML script tag with the specified source. """ return '<script type="text/javascript" src="{}"></script>'.format(source)
def strnbytes(nbytes): """ Return number of bytes in a human readable unit of KiB, MiB or GiB. Parameter --------- nbytes: int Number of bytes, to be displayed in a human readable way. Example ------- >>> a = np.empty((100,100)) >>> print(strnbytes(a.nbytes)) 78.125 KiB """ if nbytes < 1024: return str(nbytes) + ' bytes' elif nbytes < 1048576: return str(nbytes / 2**10) + ' KiB' elif nbytes < 1073741824: return str(nbytes / 2**20) + ' MiB' else: return str(nbytes / 2**30) + ' GiB'
def contains_nonascii_characters(string): """ check if the body contain nonascii characters""" for c in string: if not ord(c) < 128: return True return False
def straight_line(x, m, b): """ `line <https://en.wikipedia.org/wiki/Line_(geometry)#On_the_Cartesian_plane>`_ .. math:: f(x) = mx+b """ return m * x + b
def construct_workflow_name(example, workflow_engine): """Construct suitable workflow name for given REANA example. :param example: REANA example (e.g. reana-demo-root6-roofit) :param workflow_engine: workflow engine to use (cwl, serial, yadage) :type example: str :type workflow_engine: str """ output = '{0}.{1}'.format(example.replace('reana-demo-', ''), workflow_engine) return output
def make_kd_tree(points, dim, i=0): """ Build a KD-Tree for fast lookup. Based on a recipe from code.activestate.com """ if len(points) > 1: points.sort(key=lambda x: x[i]) i = (i + 1) % dim half = len(points) >> 1 return ( make_kd_tree(points[: half], dim, i), make_kd_tree(points[half + 1:], dim, i), points[half]) elif len(points) == 1: return (None, None, points[0])
def pobox(to_parse=None): """ Returns the mailing address for the PO box :param to_parse: :return: """ output = "You can send stuff to me at the following address: \n" \ "7241 185th Ave NE \n" \ "# 2243 \n" \ "Redmond, WA 98073" return output
def solution(A): """ https://app.codility.com/demo/results/trainingBY9CAY-RBU/ :param A: :return: """ len_ar = len(A) + 1 sum_length = int(len_ar * (len_ar + 1) / 2) return sum_length - sum(A)
def get(db, key): """ Get value by given key """ value = db.get(key) if value is None: return None return value
def coords_to_xyz(labels, coords): """ Displays coordinates """ s = "" for i in range(len(coords)): s += labels[i] + " " + str(coords[i][0]) + " " + \ str(coords[i][1]) + " " + str(coords[i][2]) + "\n" return s
def copy_dict_or_new(original: dict) -> dict: """Makes a copy of the original dict if not None; otherwise returns an empty dict. """ if original is None: return dict() return dict(original)
def _isSubsequenceContained(subSequence, sequence):# pragma: no cover """ Checks if the subSequence is into the sequence and returns a tuple that informs if the subsequence is into and where. Return examples: (True, 7), (False, -1). """ n = len(sequence) m = len(subSequence) for i in range(n-m+1): equal = True for j in range(m): equal = subSequence[j] == sequence[i+j] if not equal: break if equal: return True, i return False, -1
def count_rectangles(m: int, n: int) -> int: """Returns the number of rectangles in an m by n rectangular grid.""" return m * (m + 1) * n * (n + 1) // 4
def initialise_costs_to_zero(tree_types): """ This method returns a dictionary cost, where each key is an element in the list tree_types and each value is 0 :param tree_types: A list of tree types that represent the keys of the dictionary :return: The dictionary cost where each value is set to 0 """ cost = {} for tree_type in tree_types: cost[tree_type] = 0 return cost
def get_path_from_finish(current): """Traces back the path thourgh parent-nodes""" backwards = [] while current: backwards.append(current.location) current = current.parent backwards.reverse() return backwards
def filter_imgs(bbox, min_size=None, format='xywh'): """Filter image acoording to box size. Args: min_size (int | float, optional): The minimum size of bounding boxes in the images. If the size of a bounding box is less than ``min_size``, it would be add to ignored field. Default: None. bbox (numpy.ndarray or list): Bouding box. format (str): Format of box. """ if min_size is not None: if format == 'xyxy': w = bbox[2] - bbox[0] h = bbox[3] - bbox[1] else: w = bbox[2] h = bbox[3] return w < min_size or h < min_size else: return False
def _StringSetConverter(s): """Option value converter for a comma-separated set of strings.""" if len(s) > 2 and s[0] in '"\'': s = s[1:-1] return set(part.strip() for part in s.split(','))
def __has_number(word): """Check numbers""" return any(char.isdigit() for char in word)
def sum_even_fib_numbers(n): """Sum even terms of Fib sequence up to n""" assert n >= 0 total = 0 current_term = 1 last_term = 1 while current_term <= n: if not current_term%2: total += current_term current_term, last_term = current_term + last_term, current_term return total
def get_size(size): """Get size in readable format""" units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"] size = float(size) i = 0 while size >= 1024.0 and i < len(units): i += 1 size /= 1024.0 return "%.2f %s" % (size, units[i])
def create_token_content_id(iteration): """ :param iteration: :return: """ return 'tokenContent' + iteration
def GetDeleteResultsPathInGCS(artifacts_path): """Gets a full Cloud Storage path to a destroy-results file. Args: artifacts_path: string, the full Cloud Storage path to the folder containing deletion artifacts, e.g. 'gs://my-bucket/artifacts'. Returns: A string representing the full Cloud Storage path to the destroy-results JSON file. """ return '{0}/destroy-results.json'.format(artifacts_path)
def parse_sequence(directions): """Parse textual representation of sequence of directions into a list.""" return [direction.upper() for direction in directions.split(',')]
def assignment_one_param(arg): """Expected assignment_one_param __doc__""" return "assignment_one_param - Expected result: %s" % arg
def every_n(sequence, n=1): """ Iterate every n items in sequence. :param sequence: iterable sequence :param n: n items to iterate """ i_sequence = iter(sequence) return list(zip(*[i_sequence for i in range(n)]))
def count_words(tokenized_sentences): """ Count the number of word appearence in the tokenized sentences Args: tokenized_sentences: List of lists of strings Returns: dict that maps word (str) to the frequency (int) """ word_counts = {} # Loop through each sentence for sentence in tokenized_sentences: # complete this line # Go through each token in the sentence for token in sentence: # complete this line # If the token is not in the dictionary yet, set the count to 1 if token not in word_counts.keys(): # complete this line word_counts[token] = 1 # If the token is already in the dictionary, increment the count by 1 else: word_counts[token] += 1 return word_counts
def window_historical_load(historical_load, window_begin, window_end): """Filter historical_load down to just the datapoints lying between times window_begin and window_end, inclusive.""" filtered = [] for timestamp, value in historical_load: if timestamp >= window_begin and timestamp <= window_end: filtered.append((timestamp, value)) return filtered
def month_int_to_str(month_idx: int) -> str: """Converts an integer [1-12] into a string of equivalent month.""" switcher = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December", } return switcher.get(month_idx, f"ERROR: input {month_idx} not found in switcher")