content
stringlengths
42
6.51k
def concat_list(l1, l2): """ # Notes Appends each element of l2 to the end of l1, keeping the order of l2. # Arguments - l1: - l2: # Returns list l1 with length equals to len(l1) + len(l2). """ for i in l2: l1.append(i) return l1
def parse_instruction(instruction): """Parse instruction to modes and opcode.""" opcode = instruction % 100 result_modes = [] modes = instruction // 100 for _ in range(3): result_modes.append(modes % 10) modes = modes // 10 return result_modes, opcode
def filter_comments(tree): """Filter comment nodes from parsed configurations.""" def traverse(tree): """Generator dropping comment nodes""" for key, values in tree: if isinstance(key, list): yield [key, filter_comments(values)] else: if k...
def get_list(list_var): """Returns empty string if variable is None.""" if list_var: return list_var else: return ""
def nt_escape(node_string): """Properly escape strings for n-triples and n-quads serialization.""" output_string = '' for char in node_string: if char == u'\u0009': output_string += '\\t' elif char == u'\u000A': output_string += '\\n' elif char == u'\u000D': ...
def type2label_dict(types): """ Turn types into labels INPUT: types-> types of cell present in the data RETURN celltype_to_label_dict-> type_to_label dictionary """ all_celltype = list(set(types)) celltype_to_label_dict = {} for i in range(len(a...
def getvalue(tok): """Extract the string value from a token with default ''""" if tok: return tok.value else: return ''
def rotmol(numpoints, x, u): """ Rotate a molecule Parameters numpoints: The number of points in the list (int) x: The input coordinates (list) u: The left rotation matrix (list) Returns out: The rotated coordinates o...
def decode_reply(reply_code): """ Returns True if the RETS request was successful, otherwise False Intended to fill the response dict's 'ok' field as an alternative to the RETS specification's wonky reply code bullshit. :param reply_code: a RETS reply code :type reply_code: str :rtype: boo...
def get_max(val, val_max, idx, idx_max): """Function to get the maximum value.""" if val > val_max: return val, idx else: return val_max, idx_max
def clusters_to_pixel_set(clusters): """ Converts a list of clusters to a set of pixels. This function has no callers and is usually used as a one-liner. Parameters ---------- clusters : list of list of tuple The outer list is a list of clusters. Each cluster is a list of (i, j) ...
def assign_reference_name(config): """ Assigns bucket name to reference name if reference name doesn't exist. Args: config(dict) Returns: dict: formatted config """ for bucket in config["buckets"]: if bucket.get("referenceName") is None: ...
def enwidget(a, b): """ Provide some values for the L{widget} template. """ return {"a": a, "b": b}
def doesnt_raise(function, message=''): """ The inverse of raises(). Use doesnt_raise(function) to test that function() doesn't raise any exceptions. Returns the result of calling function. """ if not callable(function): raise ValueError("doesnt_raise should take a lambda") try: ...
def consecutive_repetitions(string): """ Given a non-empty string, it returns a substring containing the consecutive repetitions of the first character of the original string. @args: - string (str): the string to be evaluated. """ if len(string) == 1: return string ...
def generate_couples(POP,S=2,shape="cycle"): """Generates couplings between landscapes (external interaction) Args: POP (int): Number of landscapes (population size) S (int): Number of landscapes considered for external bits shape (str): A network topology. Takes values 'cycle' (defaul...
def created_but_unused_labels_exist(byte_labels): """ Check whether a label has been created but not used. If so, then that means it has to be called or specified later. """ return (False in [label["definition"] for label in byte_labels.values()])
def validate_license(license): """Validate the license. Make sure the provided license is one that exists within the Bear templates. Parameters ---------- license : str or unicode The name of the license to assign the package. Will raise if the license does not exist. Retu...
def rreplace(a, b, string): """ Replaces the tail of the string. """ if string.endswith(a): return string[:len(string)-len(a)] + b return string
def fix_misspelled_words2(text): """ Fixes the misspelled words on the specified text (uses predefined misspelled dictionary) :param text: The text to be fixed :return: the fixed text """ mispelled_dict = {'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling',...
def num_added_features(include_am, include_lm): """ Determine the number of added word-level features (specifically AM and LM) """ added_feature_count = 0 if include_am: added_feature_count += 1 if include_lm: added_feature_count += 1 return added_feature_count
def maximize(pyramid): """Recursively find the maximum path for the pyramid""" row = len(pyramid) - 2 #last row remains unchanged while row >= 0: numItems = row + 1 for i in range(numItems): maxNext = pyramid[row+1][i] if maxNext < pyramid[row+1][i+1]: ...
def filter(pred, seq): """Keeps elements in seq only if they satisfy pred. >>> filter(lambda x: x % 2 == 0, [1, 2, 3, 4]) [2, 4] """ "*** YOUR CODE HERE ***" lst = [] for item in seq: if pred(item): lst.append(item) return lst
def application_error(e): """Return a custom 500 error.""" return 'Sorry, unexpected error', 500
def empty_string(s: str) -> str: """Return an empty string if s is None""" if str(s).replace(" ", "") == "": return "" else: return str(s) if s else ""
def roman_to_integer(roman): """ Question 7.9: Convert from roman numeral to decimal """ values = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, } pairs = { 'I': None, 'V': 'I', 'X': 'I', ...
def find_next_non_blank_token(tokens, i): """ Find next non-blank token after index i (including i). Args: tokens (list[str]): a string token list. i (int): the position to search. Returns: If any token is found, return the found token. Otherwise, return None. """ ...
def reverse_array(a_list): """ https://www.hackerrank.com/challenges/01_arrays-ds/problem We can reverse an array by simply providing the step value in list slice parameters -1 means go backwards one by one """ return a_list[::-1]
def S_scale_values(_data_list, _factor): """ Returns data samples where values are scaled by the factor. """ s_data = [] ds = len(_data_list) for i in range(ds): s_data.append(_data_list[i]*_factor) return s_data
def _find_or_add_model(model, umap, keys): """Return integer node for given valuation. If absent, then a fresh node is created. @type model: `dict` @type umap: `dict` """ u = tuple(model[k] for k in keys) u = umap.setdefault(u, len(umap)) return u
def get_build_url(service_name, bb_hash): """ compare the service name to links in the superjenkins_data set the build_url when a url contains words matching the lookup service name :param cached_array: all the data from super jenkin :param lookup_word: the service keywords a string such as "telemeo...
def intersperse(lst, item): """Insert item between each list item.""" result = [item] * (len(lst) * 2 - 1) result[0::2] = lst return result
def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" print('Running merge_two_dicts') z = x.copy() z.update(y) return z
def as_signed(v, nbits = 32): """ Returns a number as signed. The number of bits are specified by the user. The MSB holds the sign. """ return -(( ~v & ((1 << nbits)-1) ) + 1) if v & (1 << nbits-1) else v
def _transpose(target_list): """Transpose the given list of lists. Args: target_list (list[list[object]]): List of list that will be transposed Returns: list[list[object]]: Transposed list of lists """ return list(map(list, zip(*target_list)))
def format_playtest_message(data): """ Format playtest message to post to Discord. """ res = '' if data['description']: res += '{}\n'.format(data['description']) for line in data['targets']: completed = '~~' if line['completed'] else '' user = ' (**{}**)'.format(line['user']...
def parse_range_header(specifier, len_content): """Parses a range header into a list of pairs (start, stop)""" if not specifier or "=" not in specifier: return [] ranges = [] unit, byte_set = specifier.split("=", 1) unit = unit.strip().lower() if unit != "bytes": return [] ...
def is_root_soul(s): """ Returns a boolean indicating whether the key s is a root soul. Root soul is in the form 'schema://id' """ return "://" in s
def bent(x,y,*args): """ Smashes points into negative xy. """ if x >= 0: if y >= 0: return x, y else: return x, y/2 else: if y >= 0: return 2*x, y else: return 2*x, y/2 return
def iconcat(a, b): """Same as a += b, for a and b sequences.""" if not hasattr(a, '__getitem__'): msg = "'%s' object can't be concatenated" % type(a).__name__ raise TypeError(msg) a += b return a
def reverse_array_dict(dictionary): """ Returns a reversed version a dictionary of keys to list-like objects. Each value in each list-like becomes a key in the returned dictionary mapping to its key in the provided dictionary. """ return_dict = {} for label, values in dictionary.items(): ...
def _slim_extension(resource, key): """ The only extension to return is Death Notification """ return [ addr for addr in resource[key] if addr["url"] == "https://fhir.nhs.uk/R4/StructureDefinition/Extension-UKCore-DeathNotificationStatus" ]
def get_gains_and_vis_from_sol(sol): """Splits a sol dictionary into len(key)==2 entries, taken to be gains, and len(key)==3 entries, taken to be model visibilities.""" g = {key: val for key, val in sol.items() if len(key) == 2} v = {key: val for key, val in sol.items() if len(key) == 3} return g, ...
def is_at_least_one_not_none(*args): """ >>> is_at_least_one_not_none(1, 2, 3) True >>> is_at_least_one_not_none(None, 2, 3) True >>> is_at_least_one_not_none(1, None, 3) True >>> is_at_least_one_not_none(1, 2, None) True >>> is_at_least_one_not_none(1, None, None) ...
def tag2seg(tags): """transform a tag sequence to a segmentation sequence. Args: tags (list): ['s', 's', 'b', 'e', 's', 'b', 'e', 'b', 'e', 'b', 'e'] Returns: segs (list): [(0, 1), (1, 2), (2, 4), (4, 5), (5, 7), (7, 9), (9, 11)] """ start = 0 end = 0 segs = [] for tag...
def dedent(s): """Remove leading spaces from the first line of a string, all common leading indentation (spaces only) from subsequent lines, strip trailing spaces from all lines and replace single newlines prior to lines with the common indentation with spaces. Lines with additional indentation are kept...
def helper(target_topL,target_bottR,xlike_topL,xlike_bottR,Ishape): """ (x,y) / (width, height) input: the topleft and bottom right coordinate for special character and x-like character respectively the shape of input image ! For convenience, we call the specical character ...
def connectChunk(key, chunk): """ Parse Storm Pipe CONNECT Chunk Method """ schunk = chunk[0].strip().split() result = {'slinkNumber': schunk[1], 'upSjunc': schunk[2], 'downSjunc': schunk[3]} return result
def turn(board, symbol): """ :param board: Contains the current state of the game :param symbol: Contains your symbol on the board - either X if you are the first player or O if you are the 2nd. :return: x_pos, y_pos where your AI wants to place a stone """ for x_pos, columns in enumerate(board)...
def searchdict2list(inputdict, search): """transfrom the search output to a list displayable on the site """ outputlist = [] for filespec, lines in sorted([x for x in inputdict.items()]): if not lines: continue dirname, filename = filespec if dirname: file...
def check_continuity(charges): """takes a list of charges and returns the length of the longest continuous consecutive stretch """ if not charges: return 0 longest_streak = 1 streak = 1 previous = charges[0] for c in charges[1:]: if c == previous + 1: streak += 1 ...
def score_by_event_threat_level(event, attributes): """ Score based on exponential of an event's threat level """ score = 0 if event["threat_level_id"] == "1": # High score += 100 elif event["threat_level_id"] == "2": # Medium score += 50 elif event["threat_level_id"] == "3": # L...
def getter(value, arg): """ Given an object `value`, return the value of the attribute named `arg`. `arg` can contain `__` to drill down recursively into the values. If the final result is a callable, it is called and its return value used. """ if '__' in arg: # Get the value of the ...
def allclose(a, b, tol=1e-7): """Are all elements of a vector close to one another""" return all([abs(ai - bi) < tol for ai, bi in zip(a, b)])
def is_background_tile(bb_list, bb_range): """ Method to check background tile :param bb_list: Data envelope list :param bb_range: Tile view range :return: outside_x or outside_y """ outside_x = True outside_y = True for data_envelope in bb_list: if(not((bb_range[0] < data_en...
def solve_1(x): """Returns the sum of all digits that match the next digit in the list (considered circular)""" x = str(x) + str(x)[0] return sum([int(x[i]) for i in range(len(x)-1) if x[i] == x[i+1]])
def prevnode(edges, component): """get the pervious component in the loop""" e = edges c = component n2c = [(a, b) for a, b in e if type(a) == tuple] c2n = [(a, b) for a, b in e if type(b) == tuple] node2cs = [(a, b) for a, b in e if b == c] c2nodes = [] for node2c in node2cs: c2...
def listed_dict_to_dict_1d(dict_in): """Convert listed dict to dict. Args: dict_in (dict): input dict (listed dic) Returns: (dict): dict """ assert isinstance(dict_in, dict) dict_out = dict_in for key, value in dict_out.items(): dict_out.update({key: value[0]}) ...
def _fortran_float_converter(in_string: bytes) -> bytes: """ This utility converts fortran double precision float strings to python float strings by replacing D with e :param in_string: The fortran string containing double precision floats :return: The string ready for ingest by python float utilities ...
def verse(bottle): """Number of the bottles""" next_bottle = bottle - 1 s1 = '' if bottle == 1 else 's' s2 = '' if next_bottle == 1 else 's' num_next = 'No more' if next_bottle == 0 else next_bottle return '\n'.join([ f'{bottle} bottle{s1} of beer on the wall,', f'{bottle} bottl...
def _idnaBytes(text): """ Convert some text typed by a human into some ASCII bytes. This is provided to allow us to use the U{partially-broken IDNA implementation in the standard library <http://bugs.python.org/issue17305>} if the more-correct U{idna <https://pypi.python.org/pypi/idna>} package is ...
def topological_sort(elems): """ Return a list of elements sorted so that their dependencies are listed before them in the result. :param elems: specifies the elements to sort with their dependencies; it is a dictionary like `{element: dependencies}` where `dependencies` is a collection of ...
def strZip(list1, list2, string): """ Return a list of strings of the form x1stringx2 where x1 and x2 are elements of list1 and list2 respectively. """ result = [] for x1, x2 in zip(list1, list2): result.append(str(x1)+string+str(x2)) return result
def filter(list, attribute, value, return_attribute=None): """Take a list and returns match objects (or list of attributes from those objects) where list object.attribute == value""" if return_attribute == None: matches = [match for match in list if match[attribute] == value ]; else: matches...
def link(text, url): """Return formatted hyperlink.""" return '<a href="{}">{}</a>'.format(url, text)
def _compare_groups(group_a, group_b): """ Compares server group_a with server_group b Returns: bool: True if specified values are equal, otherwise false """ return (group_a['policies'] == group_b['policies'] and group_a['tenant'] == group_b['tenant'] and group_a['n...
def count_media_packages(distribution_artefacts): """ Count media packages in nested list. :param distribution_artefacts: Nested list containing distribution artefacts mapped to media packages and tenants :type distribution_artefacts: dict :return: Amount of media packages :rtype: int """ ...
def decimalToBinary( dec, bitmaplen): """This function converts decimal number to binary and prints it""" bin = [] while bitmaplen != 0 : remainder = dec % 2 dec = dec // 2 bin.append(remainder) bitmaplen -= 1 return bin
def no_or_clauses (phrase): """ Returns TRUE if <phrase> contains no OR lists.""" for x in phrase: if isinstance(x,list) and x[0] == '@': return False return True
def calc_reward(p_i, winning_price, n_winning_price, reservation_price, m_consumer): """ A function that calculates the reward given a simple Bertrand environment with homogenous goods. Use calc_winning_price() to retrieve winning_price, n_winning_price for the given market prices first. Args:...
def get_key0_compare(adict): """Gets the "first" key in a dictionary The entry is kind of irrelevant. """ keys = list(adict.keys()) return keys[0]
def check_game_status(board): """Checks if the game is over.""" cond1 = board[0] == board[1] and board[1] == board[2] cond2 = board[3] == board[4] and board[4] == board[5] cond3 = board[6] == board[7] and board[7] == board[8] cond4 = board[0] == board[3] and board[3] == board[6] cond5 = board[1...
def make_cache_key(visitor_key): """ make the cache key for visitor """ return 'visitor_%s' % (visitor_key)
def DefaultDecoder(payload): """Default decoder for API payloads. The default decoder is used when a decoder is not found in the DECODER_MAP. This will stick the body of the response into the 'data' field. """ return { 'resource': { 'data': payload, }, }
def get_header_tokens(headers, key): """ Retrieve all tokens for a header key. A number of different headers follow a pattern where each header line can containe comma-separated tokens, and headers can be set multiple times. """ toks = [] for i in headers[key]: for j in i...
def join_nonempty(l): """ Join all of the nonempty string with a plus sign. >>> join_nonempty(('x1 + x2 + x1:x2', 'x3 + x4')) 'x1 + x2 + x1:x2 + x3 + x4' >>> join_nonempty(('abc', '', '123', '')) 'abc + 123' """ return ' + '.join(s for s in l if s != '')
def strip_double_quotes(item): """ Remove double quotes and the beginning and end of string """ new_item = item if item.startswith('"') and item.endswith('"'): new_item = item[1:-1] return new_item
def task(event, _context): """ Task takes an event and returns it with test values added """ return {"inputData": event['input']['initialData'], "configInputData": event['config']['configData'], "newData": {"newKey1": "newData1"}}
def is_string(value, arg_name, logger=None): """ Verifies whether a parameter is correctly defined as string. :param value: value of the parameter :param arg_name: str, parameter name :param logger: logger instance :return: boolean, True if value is a string, False otherwis...
def hailstone(n): """Print out the hailstone sequence starting at n, and return the number of elements in the sequence. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ "*** YOUR CODE HERE ***" if n == 1: print(1) return 1 elif n % 2 == 0...
def get_stops(flight_details): """ Takes an array of 'stopDetails' and returns a string delimited by pipes describing the path """ ret = '' for item in flight_details: if len(ret) > 0: ret += "|" ret += "{}-{}".format(item["originationAirportCode"],item["destinationAirportCode"]) return ...
def _fixslash(s): """ Fix windowslike filename to unixlike - (#ifdef WINDOWS)""" s = s.replace("\\", "/") if s[0] != "/" and s[1] == ":": s = s[2:] # @@@ Hack when drive letter present return s
def patient_form(first_name, last_name, patient_id, gender, birthdate): """OpenMRS Short patient form for creating a new patient. Parameters OpenMRS form field Note first_name personName.givenName N/A last_name personName.familyName N/...
def _uniqify(alist): """ Given a list, return a list with duplicates removed. """ return list(map(list, set(list(map(tuple, alist)))))
def listMean(a): """ mean function for lists """ return sum(a)/float(len(a))
def matrix_indices(vector_idx, matrix_size): """ Convert from vector index to matrix indices. Args: vector_idx (int): Vector index. matrix_size (int): Size along one axis of the square matrix to output indices for. Returns: (int, int): Row index, column index. """ asse...
def factors_pairs(num): """ (int) -> list Builds a list of factor pairs for a positive integer <num>. for example, tuple (2, 15) is a factor pair for the number 30 because 2 x 15 is 30. Returns the list of factor-pair tuples """ return [(x, num//x) for x in range(1, num + 1) if num % x ==...
def extend_coordinates(coordinates, seq, gap=None): """Extend coordinates to a gappy sequence. >>> extend_coordinates([1, 2, 3, 4], "a-b-cd") [1, 1, 2, 2, 3, 4] """ if gap is None: gap = "-" if sum(1 for c in seq if c != gap) != len(coordinates): raise Exception('coordinates do...
def CanonicalizeAddress(addr): """Strip angle brackes from email address iff not an empty address ("<>"). Args: addr: the email address to canonicalize (strip angle brackets from). Returns: The addr with leading and trailing angle brackets removed unless the address is "<>" (in which case the string...
def flip_corner(corner: tuple) -> tuple: """ Flip a tuple of a variable amount of sides :param corner: tuple with number of sides :return: flipped clock-wise tuple """ fliped_sides: list[str] = list() for s in corner: if s == 'N': fliped_sides.append('W') elif s...
def top_k_frequent(words, k): """ Input: words -> List[str] k -> int Output: List[str] """ frequency = {} for word in words: if word in frequency: frequency[word] += 1 else: frequency[word] = 1 sorted_data = sorted(frequency, key=lambda word: (-frequ...
def input_date_comparison(user_input1, user_input2): """ Validate user input dates for comparisons between first and last dates asking user to reenter dates if first date greater than last date Parameters: user_input1 (str): First date inputed user_input2 (str): First date inputed Returns:...
def calculate_utilization(billable_hours, target_hours): """Calculates utilization as hours billed divided by target hours""" if target_hours == 0: return "Non-billable" if target_hours is None: return 'No hours submitted.' if not billable_hours: return '0.00%' return '{:.3}%...
def byte_tuple_to_int(in_tuple: tuple) -> int: """ Converts two element byte tuple (highest first) to integer. :param in_tuple: the integer to convert :return: the integer value """ if ((len(in_tuple) != 2) or not all(isinstance(x, int) for x in in_tuple) or not all(0 <= x <= 255 for x in in_tup...
def odds_ratio(target_pct, peer_pct): """ intended to calculate a lender/peers odds ratio for minority lending, based on counts of loans in mostly minority areas vs mostly majority areas this algorithm has not been vetted, so its current use is only for mocking data flow to tables """ odds_...
def reformat_element_symbol(element_string): """ Reformat the string so the first letter is uppercase and all subsequent letters lowercase Parameters ---------- element_symbol: str Returns ------- reformated element symbol """ return element_string[0].upper() + element...
def uniord(s): """ord that works on surrogate pairs. """ try: return ord(s) except TypeError: pass if len(s) != 2: raise return 0x10000 + ((ord(s[0]) - 0xd800) << 10) | (ord(s[1]) - 0xdc00)
def I02I_pow(n0, theta0, r, I0=1): """ Convert Intensity I(r) at r to I at theta_0 with power law. theata_s and r in pixel """ I = I0 / (r/theta0)**n0 return I
def get_slot_values_from_transfer_to_action_event(response): """ On a transfer to action event, MS will return the context of the chat which includes all the slot values This method will crack out those values """ rv = {} if 'value' in response: for key in response['value']: ...
def exercise3(n): """ Write a function which implements the Pascal's triangle: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 """ if n == 1: return [[1]] if n == 2: return [[1], [1, 1]] else: cont = [1] ...