content
stringlengths
42
6.51k
def add_model_field_foreign_key_to_schema(schema, options): """ :param schema: :param options: expected format, e.g for a Site code foreign key: { 'schema_field': 'Site Code', # the schema field name (or column name) 'model': 'Site', 'model_field': 'code' } :return: """ foreign_keys = schema.get('foreignKeys', []) foreign_keys.append( { 'reference': { 'resource': options['model'], 'fields': [ options['model_field'] ] }, 'fields': [ options['schema_field'] ] } ) schema['foreignKeys'] = foreign_keys return schema
def prepare_assign_to(assign_to, n_actual_targets): """Converts the value of the assign_to parameter to a list of strings, as needed. >>> prepare_assign_to('x', 1) ['x'] >>> prepare_assign_to('x', 2) ['x1', 'x2'] >>> prepare_assign_to(['x'], 1) ['x'] >>> prepare_assign_to(['a','b'], 2) ['a', 'b'] >>> prepare_assign_to(None, 3) >>> prepare_assign_to(['a'], 2) Traceback (most recent call last): ... ValueError: The number of outputs (2) does not match the number of assign_to values (1) """ if assign_to is None: return None if isinstance(assign_to, str): if n_actual_targets == 1: return [assign_to] else: return ['{0}{1}'.format(assign_to, i+1) for i in range(n_actual_targets)] if len(assign_to) != n_actual_targets: raise ValueError(("The number of outputs ({0}) does not match the number" " of assign_to values ({1})").format(n_actual_targets, len(assign_to))) return assign_to
def validateTraversal(traversalOrder: list=[], verbose: bool=False): """ Check validity of traversal order """ if traversalOrder == []: traversalOrder = [1,3,5,2,4,6] if verbose: print("Verbose message: no traversal order provided, using the default value") return traversalOrder elif len(traversalOrder) != 6: raise Exception("Traversal order must be of length 6") # Check traversal order for non-integer values for order in traversalOrder: if isinstance(order, int) == False: try: traversalOrder[traversalOrder.index(order)] = int(order) except: raise Exception(f"Traversal order must contain integer values (found {type(order)} at index {traversalOrder.index(order)} instead)") # Ensure traversal order is a list of consecutive numbers if sorted(traversalOrder) == list(range(min(traversalOrder), max(traversalOrder)+1)): raise Exception("Traversal order must be comprised of consecutive integers e.g. [1,3,5,2,4,6]") return traversalOrder
def total_power(ebeam_energy=6, peak_field=1, undulator_L=1, sr_current=0.2): """ return power in W """ return 0.633 * 1e3 * ebeam_energy ** 2 * peak_field ** 2 * undulator_L * sr_current
def matrix_search(matrix, target): """ This search is a varient of the binary search O(n + m) time O(1) space """ # start the row at the beginning row = 0 # start the col at the end first_row = matrix[0] col = len(first_row) - 1 max_rows = len(matrix) - 1 while row <= max_rows and col >= 0: if target < matrix[row][col]: col -= 1 elif target > matrix[row][col]: row += 1 else: return True return False
def count_lines_exception(filename): """ Count the number of lines in a file. If file can't be opened, treated the same as if it was empty """ try: return len(open(filename, 'r').readlines()) except (EnvironmentError, TypeError): print('Exception error') return 0
def set_paths(my_path): """ Set the absolute path to required files on the current machine. Parameters ------- my_path : str path where all the imput files are located Returns ------- reactionlist_path : str path to the file `complete_reactionlist.dat` rateconstantlist_path : str path to the file `complete_rateconstantlist.dat` free_energy_path : str path to the file 'free_energy_library.dat' """ reactionlist_path = my_path + '/data/complete_reaction_list.dat' rateconstantlist_path = my_path + '/data/complete_rateconstant_list.dat' free_energy_path = my_path + '/data/free_energy_library.dat' return reactionlist_path, rateconstantlist_path, free_energy_path
def get_tags(tags, separator=', '): """ @type tags: list @type separator: unicode """ tag_list = list() for tag in tags: tag_list.append("{0}:{1}".format(tag.get('Key'), tag.get('Value'))) if tag_list: return separator.join(tag_list)
def _is_primitive(obj): """Finds out if the obj is a "primitive". It is somewhat hacky but it works. """ return not hasattr(obj, '__dict__')
def format_node(node): """ format and return given node into dictionary """ return { "node_id": node["node_id"], "create_ts": node["create_ts"], "node_owner": node["node_owner"], "host": node["host"], "port": node["port"], "phases": node["phases"], "latency": node["latency"], "connection_attempts": node["connection_attempts"], "pass_phrase": node["pass_phrase"] }
def sum_up_nums(*nums): """(int or float) -> int or float Adds up as many numbers(separate arguments) as the caller can supply. Returns the sum of <*nums> """ cntr = 0 # Init sum zero for num in nums: cntr += num return cntr
def checkpid(pid): """return the pid of the engine""" import os return os.getpid() == pid
def print_sub_wf_links(wf_id_uuid_list, extn = "html"): """ Utility method for printing the link to sub workflow pages @param wf_id_uuid_list list of wf_id and wf_uuid """ html_content = '' if len(wf_id_uuid_list) == 0: return html_content html_content ="\n<div>" for wf_id_uuid in wf_id_uuid_list: html_content += "\n<a href ='" + str(wf_id_uuid.wf_uuid) + "." + extn + "'>" + str(wf_id_uuid.wf_uuid) + " - " + str(wf_id_uuid.dax_label) + "</a><br/>" html_content += "\n</div>" return html_content
def get_fingerprint_text(fingerprint): """Gets a fingerprint text in 01-23-45-67-89-AB-CD-EF format (no hyphens)""" return ''.join(hex(b)[2:].rjust(2, '0').upper() for b in fingerprint)
def gordon_growth_model(dividend, dividend_growth_rate, required_rate_of_return): """ Summary: Calculate the value of a stock using a gordon growth model. PARA dividend: The dividend earned over the life of the stock. PARA type: float PARA dividend_growth_rate: The growth rate in the value of the dividend every period. PARA type: float PARA required_rate_of_return: The required rate of return for the investor. PARA type: float """ dividend_period_one = dividend * (1 + dividend_growth_rate) return dividend_period_one / (required_rate_of_return - dividend_growth_rate)
def substitute_lsb(origin: int, new: str): """Receives an origin number and replace the LSB (least significant bits) with the new string, converts back to integer and returns it. Args: origin (int): origin number new (str): bits that will be inserted into the origin number LSB's Raises: Raises ValueError if the length of new exceeds the maximum value for origin. e.g `substitute_lsb(4, '111111')` Raises TypeError if origin is not a number Returns: [int] operated number Example: `substitute_lsb(240, '0101')` returns `245` """ binary_origin = bin(origin) binary_origin = binary_origin[2:] try: int(new, base=2) except TypeError: raise ValueError( "New value must be a string with a binary encoded number value." ) if len(binary_origin) < len(new): raise ValueError( f"""New value is too big to be encoded inside origin value. Origin: {binary_origin}, new: {new} """ ) else: new_binary = binary_origin[: -len(new)] + new return int(new_binary, base=2)
def missing_number(nums): """ :type nums: List[int] :rtype: int """ # x ^ y = 0, if x = y; otherwise x ^ y = 1 # suppose: # x0, x1, ..., xn complete sequence # y0, y1, ..., yn_1 missing yn # x0 ^ y0 = 0 because they are equal; same for other equal-pairs. # because 2nd sequence has lack of yn, which equals to xn, thus # final result: xn ^ 0 = xn i.e the missing number. x = 0 i = 0 while i < len(nums) + 1: x ^= i i += 1 y = 0 for e in nums: y ^= e return x ^ y
def exploit_at_2(p, p_other_lag, p_own_lag, rounder_number): """ Return 1 if the prices correspond to the price cycle used if a player uses the exploit2 strategy and zero else. """ state = (p_other_lag, p_own_lag) if p == 2 and state == (1,1): return 1 elif p == 1 and state == (4,2): return 1 elif p == 2 and state == (4,4): return 1 elif rounder_number == 1 and p == 2: return 1 else: return 0
def append_inverted(cmd): """Invert and concatenate. Returns 8 bytes. append_inverted('0xD2') >>> 0xD22D """ # print("{0:b} 0x{0:x}".format(cmd)) sequence = (cmd << 8) + (255 - cmd) # print("{0:b} 0x{0:x}".format(sequence)) return sequence
def compute_string_properties(string): """Given a string of lowercase letters, returns a tuple containing the following three elements: 0. The length of the string 1. A list of all the characters in the string (including duplicates, if any), sorted in REVERSE alphabetical order 2. The number of distinct characters in the string (hint: use a set) """ len_string = len(string) list_char = [] distinct_char = 0 for char in string: if char not in list_char: distinct_char += 1 list_char.append(char) return (len_string, sorted(list_char, reverse = True), distinct_char)
def ds_digest_type_as_text(digest_type): """Get DS digest type as mnemonic""" digest_types = { 1: 'SHA1', 2: 'SHA256' } return digest_types.get(digest_type)
def quick_sort(elements): """ Use the simple non-recursive quick sort algorithm to sort the :param elements. :param elements: a sequence in which the function __get_item__, __len__ and insert were implemented :return: the sorted elements in increasing order """ length = len(elements) if not length or length == 1: return elements stack, limit = [], [0, length - 1] while stack or limit[1] - limit[0] > 0: while limit[1] - limit[0] > 0: i, j, tail = limit[0], limit[1] - 1, limit[1] if tail - i == 1: if elements[tail] > elements[i]: i = tail else: while i < j: while i < j and elements[i] <= elements[tail]: i += 1 while j > i and elements[j] >= elements[tail]: j -= 1 if i < j: elements[i], elements[j] = elements[j], elements[i] i += 1 j -= 1 if i == j: if elements[i] < elements[tail]: i += 1 elif elements[i] > elements[tail]: i = j elements[i], elements[tail] = elements[tail], elements[i] limit.append(i) stack.append(limit) limit = [limit[0], limit[2] - 1] if stack: top = stack.pop() limit = [top[2] + 1, top[1]] return elements
def oxford_comma_text_to_list(phrase): """Examples: - 'Eeeny, Meeny, Miney, and Moe' --> ['Eeeny', 'Meeny', 'Miney', 'Moe'] - 'Black and White' --> ['Black', 'White'] - 'San Francisco and Saint Francis' --> ['San Francisco', 'Saint Francisco'] """ items = [] for subphrase in phrase.split(', '): items.extend( [item.strip() for item in subphrase.split(' and ')]) return items
def firstof(seq): """Return the first item that is truthy in a sequence. Equivalent to Djangos' firstof. Args: seq (list): A list of values. Returns: value (mixed): The output, depending on the truthiness of the input. """ if not any(seq): return '' if all(seq): return seq[0] while seq: item = seq.pop(0) if item: return item return ''
def trim(line): """Remove everything following comment # characters in line. >>> from sympy.physics.quantum.qasm import trim >>> trim('nothing happens here') 'nothing happens here' >>> trim('something #happens here') 'something ' """ if not '#' in line: return line return line.split('#')[0]
def piglatinword(inword): # type: (str) -> str """ Converts a word to Pig Latin :param inword: the original word, assumed to be just a word, no punctuation or other horsing around :type inword: str :return: the word in Pig Latin :rtype: str """ # print('Started with ' + inword) if len(inword) == 1: return inword + 'way' initcap = inword[0:1].isupper() initvowel = inword[0:1].lower() in ['a', 'e', 'i', 'o', 'u'] secondcons = inword[1:2].lower() not in ['a', 'e', 'i', 'o', 'u', 'y'] thirdcons = len(inword) >= 3 and secondcons and inword[2:3].lower() not in ['a', 'e', 'i', 'o', 'u', 'y'] retword = '' if initvowel: # print(' Initial vowel') retword = inword + 'way' else: swappos = 1 # print(' Swapping at position ' + str(swappos)) if thirdcons: swappos = 3 elif secondcons: swappos = 2 moving = inword[0:swappos].lower() staying = inword[swappos:] retword = staying + moving + 'ay' # print(' Swapped: ' + retword) if initcap: # print(' Re-capitalizing') retword = retword[0:1].upper() + retword[1:] # print(' Final word: ' + retword) return retword
def chunk(iterable, num_chunks, fillvalue=(None, None)): """break list into num_chunks chunks. Ugly. Stolen from the web somewhere. """ num = float(len(iterable)) / num_chunks chunks = [iterable[i:i + int(num)] for i in range(0, (num_chunks - 1) * int(num), int(num))] chunks.append(iterable[(num_chunks - 1) * int(num):]) return chunks
def __listify(item): """A non-splitting version of :func:`galaxy.util.listify`. """ if not item: return [] elif isinstance(item, list) or isinstance(item, tuple): return item else: return [item]
def parse_request(event): """ Parses a given request's url params. :param event: API gateway input event for GET request :returns: Parsed request params dictionary """ url_params = event.get("multiValueQueryStringParameters") if url_params is None: return {"batchId": None} batch_ids = url_params.get("batchId") if len(batch_ids) != 1: return {"batchId": None} batch_id = batch_ids[0] return { "batchId": batch_id, }
def add_reprompt(response): """ Adds a response message to tell the user to ask their question again. """ response['response']['reprompt'] = { "outputSpeech": { "type": "PlainText", "text": "Please ask your crypto price question" } } return response
def Section_f(val): """ :param val: The value of this Section """ return '\\section{' + val + '}'
def dfilter(f, l): """ Splits the list into two sublists depending on the fulfilment of a criterion. Examples -------- Define a function which tests whether an argument is even number. >>> is_even = lambda x: x % 2 == 0 Now we can split the list like this: >>> dfilter(is_even, [0, 1, 2, 3, 4, 5]) ([0, 2, 4], [1, 3, 5]) """ true = [] false = [] for e in l: if f(e): true.append(e) else: false.append(e) return (true, false)
def abundant(n): """Print all ways of forming positive integer n by multiplying two positive integers together, ordered by the first term. Then, return whether the sum of the proper divisors of n is greater than n. A proper divisor of n evenly divides n but is less than n. >>> abundant(12) # 1 + 2 + 3 + 4 + 6 is 16, which is larger than 12 1 * 12 2 * 6 3 * 4 True >>> abundant(14) # 1 + 2 + 7 is 10, which is not larger than 14 1 * 14 2 * 7 False >>> abundant(16) 1 * 16 2 * 8 4 * 4 False >>> abundant(20) 1 * 20 2 * 10 4 * 5 True >>> abundant(22) 1 * 22 2 * 11 False >>> r = abundant(24) 1 * 24 2 * 12 3 * 8 4 * 6 >>> r True """ "*** YOUR CODE HERE ***" val = 1 su = 0 while val * val <= n: if n % val == 0: print (val, '*', n // val) su = su + val if val != 1 and val * val != n: su = su + (n // val) val = val + 1 if su > n: return True else: return False
def find(objects, key, value): """ Return a list of all items in objects where the key attribute is equal to value. If value is None, objects is returned. If no objects match, an empty list is returned. """ if value is None: return objects return [o for o in objects if getattr(o, key) == value]
def modify_filter(record): """ A filter function to modify records. """ record["int"] //= 2 return record
def add(num1:int,num2:int) -> int: """add is function used to give the addition of two inputted number Args: num1 (int): first number num2 (int): second number Returns: int: addition of num1 and num2 """ result = num1+num2 return result
def write(content, path): """ Write string to utf-8 pure text file """ with open(path, "wb") as f: return f.write(content.encode("utf-8"))
def split_ons_coda_prob(string, onsets, codas): """ Guesses the split between onset and coda in a string Parameters ---------- string : iterable the phones to search through onsets : iterable an iterable of possible onsets codas : iterable an iterable of possible codas Returns ------- int best guess for the index in the string where the onset ends and coda begins """ if len(string) == 0: return None max_prob = -10000 best = None for i in range(len(string) + 1): prob = 0 cod = tuple(string[:i]) ons = tuple(string[i:]) if ons not in onsets: prob += onsets[None] else: prob += onsets[ons] if cod not in codas: prob += codas[None] else: prob += codas[cod] if prob > max_prob: max_prob = prob best = i return best
def is_string(a): """ Returns if given :math:`a` variable is a *string* like variable. Parameters ---------- a : object Data to test. Returns ------- bool Is :math:`a` variable a *string* like variable. Examples -------- >>> is_string("I'm a string!") True >>> is_string(["I'm a string!"]) False """ return True if isinstance(a, str) else False
def score_to_rating_string(av_score): """ Convert the average score, which should be between 0 and 5, into a rating. """ if av_score < 1: rating = "Terrible" elif av_score < 2: rating = "Bad" elif av_score < 3: rating = "OK" elif av_score < 4: rating = "Good" else: # Using else at the end, every possible case gets caught rating = "Excellent" return rating
def student_ranking (student_scores, student_names): """Organize the student's rank, name, and grade information in ascending order. :param student_scores: list of scores in descending order. :param student_names: list of names in descending order by exam score. :return: list of strings in format ["<rank>. <student name>: <score>"]. """ index = 0 ranking = [] for element in student_scores: ranking.append (f'{index + 1}. {student_names[index]}: {element}') index += 1 return ranking
def SedPairsToString(pairs): """Convert a list of sed pairs to a string for the sed command. Args: pairs: a list of pairs, indicating the replacement requests Returns: a string to supply to the sed command """ sed_str = '; '.join(['s/%s/%s/g' % pair for pair in pairs]) if pairs: sed_str += ';' return sed_str
def parse_rmc_status(output, lpar_id): """ Parses the output from the get_rmc_status() command to return the RMC state for the given lpar_id. :param output: Output from IVM command from get_rmc_status() :param lpar_id: LPAR ID to find the RMC status of. :returns status: RMC status for the given LPAR. 'inactive' if lpar_id not found. """ # Output example: # 1,active # 2,none # 3,none # 4,none # 5,none # Be sure we got output to parse if not output: return 'inactive' # Inspect each line for item in output: # If lpar_id matches this line's lpar_id, return that status if item.split(',')[0] == str(lpar_id): return item.split(',')[1] # If we got here, we didn't find the lpar_id asked for. return 'inactive'
def prefix_average2(s): """Return list such that, for all j, a[j] equals average of s[0],...,s[j].""" n = len(s) a = [0.0] * n # create new list of n zeros for j in range(n): a[j] = sum(s[0:j + 1]) / (j + 1) # record the average return a
def dict_to_inline_style(css_styles): """ flattens dictionary to inline style :param css_styles: obj with css styles :return: str, flattened inline styles """ inline_styles = '"' for key in css_styles: inline_styles += key + ':' + css_styles[key] + ';' inline_styles += '"' return inline_styles
def norm(xtrue, x): """This function gives the norm that is used to compute the error between two values. """ # L2 (Euclidian norm) return abs(xtrue - x)
def __get_string_variable_value(var_config_values): """ Returns the associated string value :param var_config_values: the configuration dictionary :return: the value contained in the dictionary with the key 'value' """ return var_config_values['value']
def _reverse_bits(data, bits): """Flips n number of bit. :param data: Source integer number :type data: int :param bits: The number of bits to flip :type bits: int :return: Integer :rtype: int """ if bits == 0: return data result = 0 for _ in range(bits): result <<= 1 result |= data & 0b1 data >>= 1 return result
def class_id(cls): """ Returns the full id of a *class*, i.e., the id of the module it is defined in, extended by the name of the class. Example: .. code-block:: python # module a.b class MyClass(object): ... class_id(MyClass) # "a.b.MyClass" """ name = cls.__name__ module = cls.__module__ # skip empty and builtin modules if not module or module == str.__module__: return name else: return module + "." + name
def add3(a, b): """ :param a: :param b: :return: """ print("add3") print("add 3 loggg") return a + b
def fn_trans(fn): """In : fn (function : dict) Out: list of mppings (list of items in dict) """ return list(fn.items())
def disaggregate(forecast, postcode_sectors): """ """ output = [] seen_lads = set() for line in forecast: forecast_lad_id = line['lad'] for postcode_sector in postcode_sectors: pcd_sector_lad_id = postcode_sector['properties']['lad'] if forecast_lad_id == pcd_sector_lad_id: seen_lads.add(line['lad']) seen_lads.add(postcode_sector['properties']['lad']) output.append({ 'year': line['year'], 'lad': line['lad'], 'id': postcode_sector['properties']['id'], 'population': int( float(line['population']) * float(postcode_sector['properties']['weight']) ) }) return output
def is_basic_type(signature): """Returns True if the signature is a basic type 'a', '(', '{', and 'v' are not considered basic types because they usually cannot be handled the same as other types.""" basic_types = ('b','d', 'g', 'i','n','o','q','s','t','u','x','y') return signature in basic_types
def pluck(dict_, attr_list): """ Return a dict containing the attributes listed, plucked from the given dict. """ out = {} for key in attr_list: if key in dict_: out[key] = dict_[key] return out
def format_native_name(owner, project): """ Formates the package to the owner used in elm native. >>> format_native_name('elm-lang', 'navigation') '_elm_lang$navigation' """ underscored_owner = owner.replace("-", "_") underscored_project = project.replace("-", "_") return "_{owner}${repo}".format(owner=underscored_owner, repo=underscored_project)
def MMI(a, p, m): """ According to fermat's little theorem, if m is prime. than, (a^p)%m = a%m thus we can calculate, (a^p-2)%m = (a^-1)%m which is modular multiplicative inverse of a mod m. """ if not p : return 1 tmp = MMI(a, p//2, m) % m; tmp = (tmp*tmp) % m return tmp if p%2==0 else (tmp*a % m)
def getAbsoluteSegments(path, cwd='/'): """ @param path: either a string or a list of string segments which specifys the desired path. may be relative to the cwd @param cwd: optional string specifying the current working directory returns a list of string segments which most succinctly describe how to get to path from root """ if not isinstance(path, list): paths = path.split("/") else: paths = path if len(paths) and paths[0] == "": paths = paths[1:] else: paths = cwd.split("/") + paths result = [] for path in paths: if path == "..": if len(result) > 1: result = result[:-1] else: result = [] elif path not in ("", "."): result.append(path) return result
def rotLeft(a, d): """ Simple solution by slicing and concatenate array Fast """ i = d%len(a) return a[i:] + a[:i] """ Complicated solution with queue demonstration Slow """ # queue = SimpleQueue(a) # len_a = len(a) # if d > len_a//2: # for _ in range(len_a - d): # queue.add_left(queue.remove_right()) # else: # for _ in range(d): # queue.add_right(queue.remove_left()) # # return queue.show()
def _tags_from_list(tags_list): """ Returns the list of tags from a list of tag parameter values. Each parameter value in the list may be a list of comma separated tags, with empty strings ignored. """ tags = [] if tags_list is not None: for tag in tags_list: tags.extend([t for t in tag.split(",") if t != ""]) return tags
def remove_unicode_diac(text): """Takes Arabic in utf-8 and returns same text without diac""" # Replace diacritics with nothing text = text.replace(u"\u064B", "") # fatHatayn text = text.replace(u"\u064C", "") # Dammatayn text = text.replace(u"\u064D", "") # kasratayn text = text.replace(u"\u064E", "") # fatHa text = text.replace(u"\u064F", "") # Damma text = text.replace(u"\u0650", "") # kasra text = text.replace(u"\u0651", "") # shaddah text = text.replace(u"\u0652", "") # sukuun text = text.replace(u"\u0670", "`") # dagger 'alif return text
def count_construct_memo(target, word_bank, memo={}): """Counts the number of ways that 'target' can be constructed. Args: target (str): The string to be constructed. word_bank (Iterable[str]): Collection of string from which 'target' can be constructed. Returns: int: The number of ways that the 'target' can be constructed by concatenating elements of the 'word_bank' array. """ if target in memo: return memo[target] if target == '': return 1 total_count = 0 for word in word_bank: if target.find(word) == 0: total_count += count_construct_memo(target[len(word):], word_bank) memo[target] = total_count return total_count
def line_ends_to_line_points(l_ends: list, diags: bool = False) -> list: """ Args: l_ends: list of end points defined in [[x1, y1], [x2, y2]] format diags: boolean option to evaluate diagonal lines (True) or ignore (False) Returns: list of all points in [x1, y1] format that the lines cross defined by input end points """ l_points = [] for coord in l_ends: # y1 == y2 and x1 != x2 for horizontal lines if coord[0][1] == coord[1][1] and coord[0][0] != coord[1][0]: for x_val in range(min(coord[0][0], coord[1][0]), max(coord[0][0], coord[1][0]) + 1): l_points.append([x_val, coord[0][1]]) # x1 == x2 and y1 != y2 for vertical lines elif coord[0][0] == coord[1][0] and coord[0][1] != coord[1][1]: for y_val in range(min(coord[0][1], coord[1][1]), max(coord[0][1], coord[1][1]) + 1): l_points.append([coord[0][0], y_val]) # if evaluating diagonals, assume all remaining points represent diagonals elif diags: x_dir = 1 if coord[0][0] < coord[1][0] else -1 y_dir = 1 if coord[0][1] < coord[1][1] else -1 for count in range(abs(coord[0][0] - coord[1][0]) + 1): l_points.append([coord[0][0] + count * x_dir, coord[0][1] + count * y_dir]) # if ignoring diagonals, return empty array else: return [] return l_points
def startWithArabic(Instr): """ this function return true if the given string starts with am Arabic numeral """ return Instr[:1].isdigit()
def component_str(component): """ Returns the component String value @param component: Component (currently only driver) """ switcher = { 0: 'Driver' } return switcher.get(component, 'UNKNOWN')
def get_comment(bool_var): """Convert a bool into a comment or no comment for the baci input file.""" if bool_var: return '' else: return '//'
def gram_align_right(s, line_width: int = 20): """ Format for telegram, align right. :param s: input text :param int line_width: Width :return: str """ return '`{}`'.format(str(s).rjust(line_width))
def totalIndividuals(nodeState): """This function takes a node (region) and counts individuals from every age and state. :param nodeState: The disease status of a node (or region) stratified by age. :type nodeState: A dictionary with a tuple of (age, state) as keys and the number of individuals in that state as values. :return: The total number of individuals. :rtype: float """ return sum(nodeState.values())
def _describe_keypair_response(response): """ Generates a response for describe keypair request. @param response: Response from Cloudstack. @return: Response. """ return { 'template_name_or_list': 'keypairs.xml', 'response_type': 'DescribeKeyPairsResponse', 'response': response }
def _filter_empty(x): """x is an iterable (e.g. list) function assumes that each element in the iterable is a string and is passes only non-empty strings """ new = [] for i in x: if i and i != "not": new.append(i) return new
def ct_mimetype(content_type): """Return the mimetype part of a content type.""" return (content_type or '').split(';')[0].strip()
def tuple_max(left, right): """Returns a tuple containing the max value at each index between two tuples.""" return tuple(max(a, b) for (a, b) in zip(left, right))
def _convert_fold_json_to_niigz(ids): """ Specifically converts all of the file endings in the fold json dictionary from .npy to .nii.gz. """ for key in ids.keys(): ids[key] = [file.split(".")[0] + ".nii.gz" for file in ids[key]] return ids
def _get_ring_marker(used_markers): """ Returns the lowest number larger than 0 that is not in `used_markers`. Parameters ---------- used_markers : Container The numbers that can't be used. Returns ------- int The lowest number larger than 0 that's not in `used_markers`. """ new_marker = 1 while new_marker in used_markers: new_marker += 1 return new_marker
def translate_lat_to_geos5_native(latitude): """ The source for this formula is in the MERRA2 Variable Details - File specifications for GEOS pdf file. The Grid in the documentation has points from 1 to 361 and 1 to 576. The MERRA-2 Portal uses 0 to 360 and 0 to 575. latitude: float Needs +/- instead of N/S """ return ((latitude + 90) / 0.5)
def split_canonical_name(cname): """ Split a canonical package name into (name, version, build) strings. """ return tuple(cname.rsplit('-', 2))
def scan_in_javap_comment_style(s): """ Scan method signature from Javap's comment. >>> scan_in_javap_comment_style('org/myapp/AClass$AInnerClass.aMethod:([Lorg/myapp/Data;I)V') ('org/myapp/AClass$AInnerClass', 'aMethod:([Lorg/myapp/Data;I)V') """ p = s.find(":(") assert p >= 0 claz_method, args = s[:p], s[p:] q = claz_method.rfind('.') assert q >= 0 claz = claz_method[:q] method = claz_method[q+1:] return claz, method + args
def merge_p(bi,p,bigrams): """ Calculates the merge probability by combining the probs of the bigram of words and the prob of merge. Arguments bi : bigram p : p(MG->mg) from grammar (should be 1) Returns combined probability of merge op and bigram """ (w1,w2)=bi return bigrams[w1][w2]*p
def merge_dicts(dict1, dict2, merge_func): """ Merge two dictionaries. Use merge_func to resolve key-conflicts. merge_func(k, value1, value2) returns the result of merging value1/value2. Returns a dictionary dic where dic.keys() == Union[dict1.keys(), dict2.keys()] :param dict1: :param dict2: :param merge_func: [value(dict1), value(dict2)] -> value :return: """ dic = dict(dict1) for k, v in dict2.items(): if k not in dic: dic[k] = v else: dic[k] = merge_func(k, dic[k], v) return dic
def get_py3_string_type(h_node): """ Helper function to return the python string type for items in a list. Notes: Py3 string handling is a bit funky and doesn't play too nicely with HDF5. We needed to add metadata to say if the strings in a list started off as bytes, string, etc. This helper loads """ try: py_type = h_node.attrs["py3_string_type"][0] return py_type except: return None
def modexp(base, exponent, modulus): """ Performs modular exponentiation. :return: (base ** exponent) % modulus """ # NOTE: pow() in recent versions of Python 3 does the same thing. if modulus == 1: return 0 result = 1 base %= modulus while exponent: if exponent % 2: result = (result * base) % modulus exponent >>= 1 base = (base ** 2) % modulus return result
def mentions_to_IOB2(mention_list, sentence_length): """ Convert json mentions to IOB2 tags. """ tags = ['O'] * sentence_length for mention in mention_list: tags[mention['start']] = 'B-E' for i in range(mention['start'] + 1, mention['end']): tags[i] = 'I-E' return tags
def create_logdir(method, weight, label, rd): """ Directory to save training logs, weights, biases, etc.""" return "bigan/train_logs/mnist/{}/{}/{}/{}".format(weight, method, label, rd)
def extend(i, val): """Extends a list as a copy """ ii = list(i) ii.extend(val) return ii
def to_bytes(string): """Convert string to bytes type.""" if isinstance(string, str): string = string.encode('utf-8') return string
def is_api_exception(ex: Exception) -> bool: """Test for swagger-codegen ApiException. For each API, swagger-codegen generates a new ApiException class. These are not organized into a hierarchy. Hence testing whether one is dealing with one of the ApiException classes without knowing how many there are and where they are located, needs some special logic. Args: ex: the Exception to be tested. Returns: True if it is an ApiException, False otherwise. """ return ex.__class__.__name__ == "ApiException"
def find_first_positive_missing(nums: list): """ 1. Get maximum 2. Create lookup table 3. Iterate from 0 to max 4. If i is not in lookup table, return i 5. Else return maximum + 1 :param nums: pool of numbers :return: the first positive integer missing """ if not nums: return 1 maximum = max(nums) lookup = {} for num in nums: lookup[num] = True # todo: Not sure if this complies with constant space since range creates a list of values for i in range(1, maximum): if not lookup.get(i): return i return maximum + 1
def flatten(data): """Returns a flattened version of a list. Courtesy of https://stackoverflow.com/a/12472564 Args: data (`tuple` or `list`): Input data Returns: `list` """ if not data: return data if type(data[0]) in (list, tuple): return list(flatten(data[0])) + list(flatten(data[1:])) return list(data[:1]) + list(flatten(data[1:]))
def term2(params, strain, dh_value): """Second term in expression """ return ( params["delta"] * dh_value ** 2 * params["misfit_strain"] * (params["c11"] + params["c12"]) * (strain["e11"] + strain["e22"]) )
def policy_lazy(belief, loc): """ This function is a lazy policy where stay is also taken """ act = "stay" return act
def parameter_indices(*params): """ Parameter indices """ param_inds = dict([("P_kna", 0), ("g_K1", 1), ("g_Kr", 2), ("g_Ks", 3),\ ("g_Na", 4), ("g_bna", 5), ("g_CaL", 6), ("g_bca", 7), ("g_to", 8),\ ("K_mNa", 9), ("K_mk", 10), ("P_NaK", 11), ("K_NaCa", 12), ("K_sat",\ 13), ("Km_Ca", 14), ("Km_Nai", 15), ("alpha", 16), ("gamma", 17),\ ("K_pCa", 18), ("g_pCa", 19), ("g_pK", 20), ("Buf_c", 21), ("Buf_sr",\ 22), ("Ca_o", 23), ("K_buf_c", 24), ("K_buf_sr", 25), ("K_up", 26),\ ("V_leak", 27), ("V_sr", 28), ("Vmax_up", 29), ("a_rel", 30),\ ("b_rel", 31), ("c_rel", 32), ("tau_g", 33), ("Na_o", 34), ("Cm",\ 35), ("F", 36), ("R", 37), ("T", 38), ("V_c", 39), ("stim_amplitude",\ 40), ("stim_duration", 41), ("stim_period", 42), ("stim_start", 43),\ ("K_o", 44)]) indices = [] for param in params: if param not in param_inds: raise ValueError("Unknown param: '{0}'".format(param)) indices.append(param_inds[param]) if len(indices)>1: return indices else: return indices[0]
def isTopologicalOrder(G, L): """Check that L is a topological ordering of directed graph G.""" vnum = {} for i in range(len(L)): if L[i] not in G: return False vnum[L[i]] = i for v in G: if v not in vnum: return False for w in G[v]: if w not in vnum or vnum[w] <= vnum[v]: return False return True
def check_file(path): """ This function.. :param path: :return: """ import os.path full = os.path.abspath(path) if os.path.exists(full): return full return None
def sum(arg): """ :param arg: an array of numbers :return: a total """ total = 0 for val in arg: total += val return total
def check_uniqueness_in_rows(board: list): """ Check buildings of unique height in each row. Return True if buildings in a row have unique length, False otherwise. >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215',\ '*35214*', '*41532*', '*2*1***']) True >>> check_uniqueness_in_rows(['***21**', '452453*', '423145*', '*543215',\ '*35214*', '*41532*', '*2*1***']) False >>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*553215',\ '*35214*', '*41532*', '*2*1***']) False """ for index, line in enumerate(board): if index not in (0, len(board) - 1): board_line = line[1:-1] for elem in board_line: if board_line.count(elem) > 1: return False return True
def interlis_models_dictionary(*argv): """ Combine different interlis model dictionaries :param argv: several interlis model dictionaries :return: dictionary of combined model dictionaries """ combined_dictionary = [] for arg in argv: combined_dictionary = combined_dictionary + arg return set(combined_dictionary)
def remove_slash(path: str) -> str: """Remove slash in the end of path if present. Args: path (str): Path. Returns: str: Path without slash. """ if path[-1] == "/": path = path[:-1] return path
def test_lyrics(lyrics): """ Test lyrics downloaded to detect license restrinction string: 'We are not in a position to display these lyrics due to licensing restrictions. Sorry for the inconvinience.' Also test lyrics by looking for multiple new line characters. Returns booleans accordingly """ if not lyrics: return False license_str1 = 'We are not in a position to display these lyrics due to licensing restrictions. Sorry for the inconvinience.' license_str2 = 'display these lyrics due to licensing restrictions' license_str3 = 'We are not in a position to display these lyrics due to licensing restrictions.\nSorry for the inconvinience.' # If either of license string is found in lyrics downloaded or it has less than 4 new line characters if (license_str1 in lyrics or license_str2 in lyrics or license_str3 in lyrics or lyrics.count('\n') < 4): return False return True
def pythonTypeToJSONType(value): """Convert Python data type to JSON data type""" if isinstance(value, dict): return 'object' elif isinstance(value, (list, tuple)): return 'array' elif isinstance(value, str): return 'string' elif isinstance(value, bool): return 'boolean' elif isinstance(value, (int, float)): return 'number' elif value is None: return 'null' else: return 'unknown'
def _escape_js_template_tags(s): """ Jinja Filter to escape javascript template variables. """ return '{{ ' + str(s) + ' }}'
def array_add(first, second): """ Addition with bytearrays. Since arrays allocate a specific amount of memory, this way is somewhat inefficient -- but about twice as fast as using Python's range function. """ first_array = bytearray(first) second_array = bytearray(second) first_array.extend(second_array) return len(first_array)