content
stringlengths
42
6.51k
def parse_payload_v1(event): """ Get HTTP request method/path/body for v1 payloads. """ body = event.get('body') method = event.get('httpMethod') try: package, *_ = event['pathParameters']['package'].split('/') except KeyError: package = None return (method, package, body)
def gen_random_str(length=32): """ Generate random string (letters+numbers) Args: length: string length (default: 32) """ import string import random symbols = string.ascii_letters + '0123456789' return ''.join(random.choice(symbols) for i in range(length))
def convert_mat_value(val): """Convert values specified in materials elements_vars.""" return { 'values': [float(x) for x in val['values']], 'min_value': float(val['min_value']) if val['min_value'] is not None else None, 'max_value': float(val['max_value']) if val['max_value'] is not None else None, }
def suffixer(n): """ Provides the suffix for printing out a podium spot based on the spot number. """ if n == 1: return 'st' elif n == 2: return 'nd' elif n == 3: return 'rd' else: return 'th'
def yx_to_xy(yx_grid): """Turns a y/x grid (row, column) into an x/y grid. Iterates through the yx grid keeping track of the current location, and maps that value to the corresponding position within the xy grid :param map: int[][], a typical ingested y/x grid :return: int[][], a RHR cartesian x,y grid ------------------------------------------------ yx_style_grid: 0 1 2 0 a b c == [[a,b,c], 1 d e f [d,e,f]] xy_style_grid: 1 a b c == [[d, a], 0 d e f [e, b], 0 1 2 [f, c]] """ len_x = len(yx_grid[0]) # any index works, grid should be same length anywhere. len_y = len(yx_grid) # how many y indices there are. xy_grid = [] # note that the above may change as we edit our code. I will think of a solution. # generate locations for us to follow (relative to yx) x_loc = 0 y_loc = 0 # note that the y direction is flipped while x_loc < len_x: temp = [] y_loc = 0 while y_loc < len_y: temp.append(yx_grid[len_y - y_loc - 1][x_loc]) # need to flip the y y_loc += 1 xy_grid.append(temp) x_loc += 1 return xy_grid
def valid_filename(s): """ Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. Arguments: s {str} Returns: str """ import re s = str(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '-', s)
def sizeof_fmt(num, suffix="B"): """Convert any number to human readable size. By Fred Cirera""" 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 max_(data): """Maximum of the values in the object""" maximum = data[0] for value in data: maximum = value if value > maximum else maximum return maximum
def spike_height(trending_score, x, x_old, time_boost=1.0): """ Compute the size of a trending spike. """ # Change in softened amount change_in_softened_amount = x**0.25 - x_old**0.25 # Softened change in amount delta = x - x_old softened_change_in_amount = abs(delta)**0.25 # Softened change in amount counts more for minnows if delta > 0.0: if trending_score >= 0.0: multiplier = 0.1/((trending_score/time_boost + softened_change_in_amount) + 1.0) softened_change_in_amount *= multiplier else: softened_change_in_amount *= -1.0 return time_boost*(softened_change_in_amount + change_in_softened_amount)
def add_gate_to_line(local_qasm_line, gate_symbol, qubit_index): """ Add in parallel the application of a gate on a qubit. Args: local_qasm_line: The existing line of QASM to add the gate in. gate_symbol: The symbol representing the gate. qubit_index: The index of the target qubit. Returns: The same line of QASM with the gate added. """ # if another operation is already called on this qubit, we have to put the new gate on a new line if "[" + str(qubit_index) + "]" in local_qasm_line \ or "[" + str(qubit_index) + "," in local_qasm_line \ or "," + str(qubit_index) + "," in local_qasm_line \ or "," + str(qubit_index) + "]" in local_qasm_line: local_qasm_line += "\n{} q[{}]\n".format(gate_symbol, qubit_index) # if the line is not empty, we need to consider what's already present elif local_qasm_line != "": # a bracket indicates this line is parallelized with the { gate | gate | gate } syntax if "{" in local_qasm_line: # remove } from the line and add it back at the end local_qasm_line = local_qasm_line.rstrip("}| \n") + \ " | " + \ "{} q[{}]".format(gate_symbol, qubit_index) + \ "}\n" # no bracket means we have to add the parallelization syntax ourselves else: local_qasm_line = "{" + local_qasm_line.rstrip("\n") + \ " | " + \ "{} q[{}]".format(gate_symbol, qubit_index) + "}\n" # else, if the line IS empty, we can just put this gate in directly else: local_qasm_line = "{} q[{}]\n".format(gate_symbol, qubit_index) return local_qasm_line
def parse_number_set(number_set): """ Parse a number set string to a set of integers. The string is a comma-separated range of "atoms", which may be * A single value (`1`) * A range of values (`1-5`) separated with either a dash or double dots. and these may also be negated with a leading exclamation mark. >>> parse_number_set('1-5,8-9') {1, 2, 3, 4, 5, 8, 9} >>> parse_number_set('1-5,!4') {1, 2, 3, 5} >>> parse_number_set('1,2,3') {1, 2, 3} >>> sorted(parse_number_set('-1..-5')) [-5, -4, -3, -2, -1] """ incl = set() excl = set() for atom in number_set.split(','): atom = atom.strip() if not atom: continue if atom.startswith('!'): dest = excl atom = atom[1:] else: dest = incl if '-' in atom[1:] or '..' in atom: start, end = [int(v) for v in atom.split(('..' if '..' in atom else '-'), 1)] if start > end: end, start = start, end dest.update(set(range(start, end + 1))) else: dest.add(int(atom)) return incl - excl
def get_sequence(genome, chrom, start, end, is_forward_strand=True): """Return a sequence for the genomic region. Coordinates are 0-based, end-exclusive. """ # Prevent fetching negative coordinates. start = max(start, 0) if start >= end: return '' else: seq = genome[str(chrom)][start:end] if not is_forward_strand: seq = -seq return str(seq).upper()
def url_path_join(*args): """Join path(s) in URL using slashes""" return '/'.join(s.strip('/') for s in args)
def witHelp(x): """ witHelp(x) -> (t, u) witHelp returns x as a tuple (t, u), where x = u * 2**t """ t = 0 while not (x & 1): x >>= 1 t += 1 return (t, x)
def numberSeparators(number, separator=' '): """ Adds a separator every 3 digits in the number. """ if not isinstance(number, str): number = str(number) # Remove decimal part str_number = number.split('.') if len(str_number[0]) <= 3: str_number[0] = str_number[0] else: str_number[0] = numberSeparators(str_number[0][:-3]) + separator + str_number[0][-3:] # Verify if the var "number" have a decimal part. if len(str_number) > 1: return str_number[0] + '.' + str_number[1] return str_number[0]
def calculate_declining_funds(starting_amount, interest_rate, stipend_amount): """ If I want to take out a big chunk every year, how many years will it last? :param starting_amount: The amount of money the bank has to start with. :type starting_amount: double :param interest_rate: The rate that interest is being added into the bank. :type interest_rate: float :param stipend_amount: The amount taken out each year for a stipend. :type stipend_amount: float :return: The amount of years until funds deplete, the last stipend amount. """ # We are not losing anything. if stipend_amount <= 0: return -1, -1 current_amount = starting_amount last_stipend_amount = 0 years = 0 while current_amount > 0: # Funds are taken out at the beginning of each year, to accrue interest regardless. current_amount += (current_amount * interest_rate) # if we are on the last iteration if current_amount - stipend_amount <= 0: last_stipend_amount = stipend_amount - current_amount years += 1 current_amount -= stipend_amount return years, last_stipend_amount
def part_decode(part): """Decode a part of a JSON pointer. >>> part_decode("foo") 'foo' >>> part_decode("~0foo") '~foo' >>> part_decode("foo~0") 'foo~' >>> part_decode("~1foo") '/foo' >>> part_decode("foo~1") 'foo/' >>> part_decode("f~1o~0o") 'f/o~o' >>> part_decode("~00") '~0' >>> part_decode("~01") '~1' >>> part_decode("0") '0' """ return part.replace("~1", "/").replace("~0", "~")
def scale_norm(norm, min_distance, max_distance): """Convert network's sigmoid output into distance prediction""" return min_distance + max_distance * norm
def _container_name(name): """ For a given container or well name, return just the container name. Parameters ---------- name : str Returns ------- str """ return name.split("/", 1)[0]
def linspace(start, end, totalelem): """ Basically same as numpy.linspace. Cut [start, end] into an array with totalelem elements (including start and end) that are an even distance apart """ if totalelem == 1: return [start] gaps = totalelem - 1 dist = (end-start)/gaps return [start + (i*dist) for i in range(totalelem)]
def get_shape_from_component(component, component_name='vtx'): """ Given a component, returns the associated shape :param component: str :param component_name: str, component type ('vtx', 'e', 'f' or 'cv') :return: str """ component_shape = None if component.find('.{}['.format(component_name)) > -1: split_selected = component.split('.{}['.format(component_name)) if split_selected > 1: component_shape = split_selected[0] return component_shape
def next_quarter(year, quarter, num=1): """return next quarter for Gregorian calendar""" if quarter not in range(1, 5): raise ValueError('invalid quarter') quarter -= 1 # for mod, div quarter += num year += quarter // 4 quarter %= 4 quarter += 1 # back return year, quarter
def fractional_epoch(row, *, default=None): """Given a data row, compute the fractional epoch taking batch into account. Example: Epoch 1 at batch 30 out of 100 batches per epoch would return epoch 1.3. """ if 'epoch' not in row: return default if 'batch' not in row: return row.get('epoch') return row.get('epoch') + row.get('batch') / row.get('n_batches')
def filter_pad(val, width, fillchar='0'): """Pads a number or string with fillchar to the specified width.""" return str(val).rjust(width, fillchar)
def itineraryisvalid(itinerary): """Verifies that an itinerary is able to be processed.""" itinerary = itinerary.lower() if len(itinerary) < 3: #We don't allow itineraries that don't have at least three destinations for now return False for count, i in enumerate(itinerary): if i not in ("1","2","x"): #We only allow these three symbols return False if count + 1 < len(itinerary): #We don't allow travel between the m1 and exterior realms #or the same destination twice if i == "1" and itinerary[count + 1] == "x": return False if i == "x" and itinerary[count + 1] == "1": return False if i == itinerary[count + 1]: return False return True
def divide_list(array, number): """Create sub-lists of the list defined by number. """ if len(array) % number != 0: raise Exception("len(alist) % number != 0") else: return [array[x:x+number] for x in range(0, len(array), number)]
def add_text_element(param_args): """Generates a string that represents a html text block. The input string should be wrapped in proper html tags param_args - a dictionary with the following arguments: param_args['text'] - a string returns - a string """ return param_args['text']
def hasCapLettersOnly (tok): """Returns true if token has at least one capital letter, and no lower case letters. Can also contain digits, hypens, etc.""" hasCap = False for sub in tok: if (sub.isalpha()): if (sub.islower()): return False else: hasCap = True return hasCap
def to_rgba_bytes(v: int) -> bytes: """ Converts an RGBA color int to raw bytes. """ return bytes(i & 0xFF for i in (v >> 24, v >> 16, v >> 8, v))
def get_unique_attribute_objects(graph, uniq_attrs): """Fetches objects from given scene graph with unique attributes. Args: graph: Scene graph constructed from the dialog generated so far uniq_attrs: List of unique attributes to get attributes Returns: obj_ids: List of object ids with the unique attributes """ obj_ids = {} for obj_id, obj in graph['objects'].items(): for attr, val in uniq_attrs: if obj.get(attr, '') == val: # At this point the key should not be present. assert (attr, val) not in obj_ids, 'Attributes not unique!' obj_ids[(attr, val)] = obj_id return obj_ids
def get_subkey(d, key_path): """Gets a sub-dict key, and return None if either the parent or child dict key does not exist :param d: dict to operate over :type d: dict of dicts :param key_path: dict keys path list representation :type key_path: list Example ------- >>> d = { ... 'a': { ... '1': 2, ... '2': 3, ... } ... } >>> # FIXME commented-out: order unspecified, depend on python version >>> # >>> get_subkey(d, ['a']) >>> # {'1': 2, '2': 3} >>> get_subkey(d, ['a', '1']) 2 >>> get_subkey(d, ['a', '3']) """ if len(key_path) > 1: if d.get(key_path[0]) is None: return None return get_subkey(d[key_path[0]], key_path[1:]) else: return d.get(key_path[0])
def get_actual_pool(spoiler): """Retrieves the actual item pool based on items placed in the spoiler log. :param spoiler: Spoiler log output from generator :return: dict: key: Item name value: count in spoiler """ actual_pool = {} for location, item in spoiler['locations'].items(): if isinstance(item, dict): test_item = item['item'] else: test_item = item try: actual_pool[test_item] += 1 except KeyError: actual_pool[test_item] = 1 return actual_pool
def dict_sort(dictionary): """Takes in a dictionary with integer values and outputs a list of the keys sorted by their associated values in descending order.""" return list(sorted(dictionary, key=dictionary.__getitem__, reverse=True))
def inc_code_correct(inc_type_code, inc_type_desc): """ Parses and corrects OC CAD Incident Type Description. """ if inc_type_code == 'BOX_CO': inc_type_code = 'BOX_COM' elif inc_type_code == 'BOX_RE': inc_type_code = 'BOX_RES' elif inc_type_code == 'FULL_C': inc_type_code = 'FULL_COM' elif inc_type_code == 'FULL_R': inc_type_code = 'FULL_RES' elif inc_type_desc == 'COMMERCIAL FIRE STIL': inc_type_code = 'STILL_COM' elif inc_type_desc == 'RESD FIRE STILL RESP': inc_type_code = 'STILL_RES' elif inc_type_code == 'WATERE': inc_type_code = 'WATERES' else: pass return inc_type_code
def turn_left(block_matrix, debug=False): """block turn left.""" new_block = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] for i in range(4): for j in range(4): new_block[j][3-i] = block_matrix[i][j] if debug: print(new_block) return new_block
def file_base_features(path, record_type): """Return values for BASE_SCHEMA features.""" base_feature_dict = { "record_id": path, "record_type": record_type, # "utc_last_access": os.stat(path).st_atime, "utc_last_access": 1600000000.0, } return base_feature_dict
def _extract_mc_repeated_field(data, plural, singular): """Helper to extract repeated fields from xml consistently. Without this single element lists get returned as dicts """ f = data.get(plural, {}).get(singular, []) if type(f) == list: return f else: return [f]
def _ValidateRepoToDepPathConfig(repo_to_dep_path): """Checks that the repo_to_dep_path is properly formatted. Args: repo_to_dep_path (dict): A dictionary mapping repository url to its chromium repo path. For example: { "https://boringssl.googlesource.com/boringssl.git": "src/third_party/boringssl/src", "https://chromium.googlesource.com/android_ndk.git": "src/third_party/android_ndk", "https://chromium.googlesource.com/angle/angle.git": "src/third_party/angle", ... } Returns: True if ``repo_to_dep_path`` is properly formatted, False otherwise. """ if not isinstance(repo_to_dep_path, dict): return False return True
def get_indefinite_article(noun: str) -> str: """ >>> get_indefinite_article('Elephant') 'an' >>> get_indefinite_article('lion') 'a' >>> get_indefinite_article(' ant') 'an' """ normalised_noun = noun.lower().strip() if not normalised_noun: return 'a' if normalised_noun[0] in 'aeiou': return 'an' else: return 'a'
def separate_categories(invoice_lines: dict): """ This function separates categories and counts their prices. Decimal euros are converted into integer cents. :param invoice_lines: dictionary with invoice lines :return: dictionary with separated categories """ categories = {} for invoice in invoice_lines: price = int(invoice['unit_price_net'].replace('.', '')) * invoice['quantity'] if invoice['category'] in categories: categories[invoice['category']] += price else: categories[invoice['category']] = price return categories
def flush(hand): """Return True if all the cards have the same suit.""" suits = [s for r, s in hand] return len(set(suits)) == 1
def tsv_example_row(label, title): """Return row with entity type column populated""" return [label] + [""] * (len(title) - 1)
def plural_suffix(count: int) -> str: """"s" when count is not one""" suffix = '' if count != 1: suffix = 's' return suffix
def itemfilter(fn, d): """returns {k: v for k, v in d.items() if fn(k, v)}""" return {k: v for k, v in d.items() if fn(k, v)}
def countPrimes(n): """ :type n: int :rtype: int """ if n <= 2: return 0 primes = [True] * (n) primes[0] = primes[1] = False for i in range(2, n): if primes[i]: for j in range(i*i, n, i): primes[j] = False return sum(primes)
def factorial(n): """A factorial of n (n!) is defined as the product of all positive integers less then or equal to n. According to the convention for an empty product, the value of factorial(0) (0!) is 1. >>> [factorial(i) for i in range(11)] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800] """ # The stopping criterion is when we reach 1 or less if n <= 1: return 1 # n! = n * (n-1) * (n-2) * ... * 2 * 1, therefore # n! = n * (n-1)! return n * factorial(n-1)
def is_email_link(href=None): """Utility function to determine whether the supplied href attribute is an email link.""" print("email_link()") return href and 'mailto:' in href
def convert_to_date( value=None, format="%Y-%m-%d %H:%M:%S"): """convert_to_date param: value - datetime object param: format - string format """ if value: return value.strftime(format) return ""
def return_file_read(_): """Return the lines expected to be found in the file_read test file. Args: _: Present to mimic the behavior of RawLog.get_section_* functions, but not used by the function Returns: A list of the lines in file_read.txt with trailing whitespace removed """ return ["scorevideo LOG", "File: log.mat"]
def get_authors_text(csl_item, max_length=100): """ Return string of authors like: Ching, Himmelstein, Beaulieu-Jones, Kalinin, Do, Way, Ferrero, Agapow, Zietz, Hoffman, Xie, Rosen, et al "et al" is inserted when adding another name would cause authors_text to exceed max_length. """ authors = list() keys = [ 'author', 'collection-editor', 'composer', 'container-author', 'director', 'editor', 'editorial-director', 'translator', ] for key in keys: if key in csl_item: authors = csl_item[key] break authors_text = '' for author in authors: try: # name = f"{author['given']} {author['family']}"] name = author['family'] except KeyError: if 'literal' in author: name = author['literal'] else: continue if authors_text: authors_text += ', ' if len(name) + len(authors_text) > max_length: authors_text += 'et al' break authors_text += name return authors_text
def check_provisioning_state(provisioning_state: str): """Check if the provisioning state is succeeded""" required_provisioning_state = 'Succeeded' if required_provisioning_state.lower() == provisioning_state.lower(): return True return False
def velocity(range, avg_range, volume, avg_volume): """ The average of the average of the range and volume for a period. :param range: :param avg_range: :param volume: :param avg_volume: :return: """ rng_rate = range / avg_range vol_rate = volume / avg_volume total = sum((rng_rate, vol_rate)) return round(total / 2, 2)
def width(canv): """ gets the height of the canvas :param canv: :return: integer height of the canvas """ return (canv and len(canv[0])) or 0
def get_nodetype(obj, objid): """ Returns key of the object with given ID. (eg., menu, page, etc. ) :param obj: Structure containing YAML object ( nested lists / dicts ). :param objid: YAML ID of given node. :return: Key of given ID. """ result = None if isinstance(obj, dict): for key, val in obj.items(): if val == objid: result = key elif isinstance(val, list) or isinstance(val, dict): retval = get_nodetype(val, objid) if retval is not None: result = retval elif isinstance(obj, list): for elem in obj: if isinstance(elem, list) or isinstance(elem, dict): retval = get_nodetype(elem, objid) if retval is not None: result = retval return result
def go_to_url(url, return_what, uniqid): """ xxx """ #--------------------------------- # q = [url to redirect] # # return_what = 'form' = # '<form id="form_id_xxx"><input type="hidden" value="'+ str(q) +'" id="q"></form>' # # return_what = 'link' = # 'href="javascript:{}" onclick="document.getElementById('form_id_xxx').submit(); # return false;"' # # uniqid = [a unique id to identify the form] #--------------------------------- return_data = '' return_data = 'url/?q=' + str(url) content = '' if return_what == 'form': content = '<form id="'+\ str(uniqid) +'" " action="'+ 'url/' +\ '" method="post" target="_blank"><input type="hidden" id="q" name="q" value="'+\ str(url) +'"></form>' if return_what == 'link': content = 'href="javascript:{}" onclick="document.getElementById(\''+\ str(uniqid) +'\').submit(); return false;"' return_data = content return return_data
def format_order_by(orderby: list, alias='s', similarity_col='fts_col') -> str: """ Make the api parameter 'order-by' into pony code. **Works on single table query ONLY**. :param orderby: parameter from the api, list of field to be used by the order by :param alias: table alias :param similarity_col: name of the column to use in case order by needs to be performed by similarity :return: formated code usable in a pony query """ order_by = '' for field in orderby: # is field DESC ? if field[0] == '-': field = field[1:] pattern = 'orm.core.desc({field}),' else: pattern = '{field},' # is field a real entity property ? if field != 'similarity': field = '{alias}.{field}'.format(alias=alias, field=field) else: field = 'orm.raw_sql(\'similarity("s"."{}", $search)\')'.format(similarity_col) order_by += pattern.format(field=field) return order_by[:-1]
def remove(elements, element): """ This tag removes an element from a list. :param elements: The given list of elements :type elements: list :param element: The element to be removed :type element: object :return: The list without the element :rtype: list """ try: # Copy input list to make sure it is not modified in place result = elements.copy() result.remove(element) return result except ValueError: # If the element wasn't in the list to begin with, just return the input return elements
def renumber(dictionary) : """Renumber the values of the dictionary from 0 to n :param dictionary: the partition :type dictionary: dictionary :rtype: dictionary :return: The modified partition and the number of classes """ count = 0 ret = dictionary.copy() new_values = dict([]) for key in dictionary.keys() : value = dictionary[key] new_value = new_values.get(value, -1) if new_value == -1 : new_values[value] = count new_value = count count = count + 1 ret[key] = new_value return ret, count
def _fraction_elutions(fractions): """ Given a list of fraction names, group them after removing 'FractionXX' from the end. Return a dict of { elutionname: listofindices }. Example of fraction name: Orbitrap_HeLaCE_IEF_pH3_to_10_Fraction10 """ elution_names = {} for i,fname in enumerate(fractions): ename = fname[:fname.find('_Fraction')] elution_names.setdefault(ename,[]).append(i) return elution_names
def get_peak_volumes(volumes): """Returns a list of the current peak volume at each second. Resets when volume below -72 or above 10.""" peaks = [] peak = -73 for volume in volumes: temp = peak if volume < -72: peak = -73 # Reset peak temp = '-Inf' elif volume > 10: peak = -73 # Reset peak temp = 'CLIP' elif volume > peak: peak = volume temp = volume peaks.append(temp) return peaks
def quick_sort(num_list=[]): """Quick sorts a number list""" if type(num_list) != list: raise TypeError("The argument for quick_sort must be of type list.") if len(num_list) <= 1: return num_list choice = num_list[len(num_list) // 2] greater = [num for num in num_list if num > choice] equal = [num for num in num_list if num == choice] lesser = [num for num in num_list if num < choice] return quick_sort(lesser) + equal + quick_sort(greater)
def generate_performance_payload(array, start_time, end_time, metrics): """Generate request payload for VMAX performance POST request :param array: symmetrixID :param start_time: start time for collection :param end_time: end time for collection :param metrics: metrics to be collected :returns: payload dictionary """ return {'symmetrixId': str(array), "endDate": end_time, "startDate": start_time, "metrics": metrics, "dataFormat": "Average"}
def call_warpper(callback, request, args): """ change the calling policy according to the parameters of callback function *beautiful code ,oopssssssss """ varnames = callback.__code__.co_varnames argcount = callback.__code__.co_argcount if argcount != 0 and varnames[0] == "request": return callback(request, *args) return callback(*args)
def create_binding(subject, displayId, version, name, description, _type, role, sbol_type, order_by, percentMatch=-1, strandAlignment='N/A', CIGAR='N/A'): """ Creates bindings to be sent to SBH Arguments: subject {string} -- URI of part displayId {string} -- DisplayId of part version {int} -- Version of part name {string} -- Name of part description {string} -- Description of part _type {string} -- SBOL type of part role {string} -- S.O. role of part order_by {?} -- ? Keyword Arguments: percentMatch {number} -- Percent match of query part to the target part (default: {-1}) strandAlignment {str} -- Strand alignment of the query part relatve to the target part (default: {'N/A'}) CIGAR {str} -- Alignment of query part relative to the target part (default: {'N/A'}) Returns: Dict -- Part and its information """ binding = {} if subject is not None: binding["subject"] = { "type": "uri", "datatype": "http://www.w3.org/2001/XMLSchema#uri", "value": subject } if displayId is not None: binding["displayId"] = { "type": "literal", "datatype": "http://www.w3.org/2001/XMLSchema#string", "value": displayId } if version is not None: binding["version"] = { "type": "literal", "datatype": "http://www.w3.org/2001/XMLSchema#string", "value": version } if name is not None: binding["name"] = { "type": "literal", "datatype": "http://www.w3.org/2001/XMLSchema#string", "value": name } if description is not None: binding["description"] = { "type": "literal", "datatype": "http://www.w3.org/2001/XMLSchema#string", "value": description } if _type is not None: binding["type"] = { "type": "uri", "datatype": "http://www.w3.org/2001/XMLSchema#uri", "value": _type } if role is not None: binding["role"] = { "type": "uri", "datatype": "http://www.w3.org/2001/XMLSchema#uri", "value": role } if sbol_type is not None: binding["sboltype"] = { "type": "uri", "datatype": "http://www.w3.org/2001/XMLSchema#uri", "value": sbol_type } if order_by is not None: binding["order_by"] = order_by if percentMatch != -1: binding["percentMatch"] = { "type": "literal", "datatype": "http://www.w3.org/2001/XMLSchema#string", "value": str(percentMatch) } if strandAlignment != 'N/A': binding["strandAlignment"] = { "type": "literal", "datatype": "http://www.w3.org/2001/XMLSchema#string", "value": strandAlignment } if CIGAR != 'N/A': binding["CIGAR"] = { "type": "literal", "datatype": "http://www.w3.org/2001/XMLSchema#string", "value": CIGAR } return binding
def check_player_win(board, token) : """ board: list of strings representing tic-tac-toe board where a row is a string of 3 tokens token: string representing either x or o Check 8 possible winning combinations: 3 rows matching the token, 3 columns matching the token, or 2 diagnols matching the token. Returns True if the token got 3 in a row, and False otherwise. """ row1 = (board[0][0] == board[0][1] == board[0][2] == token) row2 = (board[1][0] == board[1][1] == board[1][2] == token) row3 = (board[2][0] == board[2][1] == board[2][2] == token) col1 = (board[0][0] == board[1][0] == board[2][0] == token) col2 = (board[0][1] == board[1][1] == board[2][1] == token) col3 = (board[0][2] == board[1][2] == board[2][2] == token) diag1 = (board[0][0] == board[1][1] == board[2][2] == token) diag2 = (board[2][0] == board[1][1] == board[0][2] == token) return row1 or row2 or row3 or col1 or col2 or col3 or diag1 or diag2
def _path_to_name(path, prefix = None, suffix = None): """Converts a path string to a name suitable for use as a label name. Args: path: A path as a `string`. prefix: Optional. A string which will be prefixed to the namified path with an underscore separating the prefix. suffix: Optional. A `string` which will be appended to the namified path with an underscore separating the suffix. Returns: A `string` suitable for use as a label name. """ prefix_str = "" if prefix != None: prefix_str = prefix + "_" if not prefix.endswith("_") else prefix suffix_str = "" if suffix != None: suffix_str = "_" + suffix if not suffix.startswith("_") else suffix return prefix_str + path.replace("/", "_").replace(".", "_") + suffix_str
def Flatten(value): """Flattens nested lists/tuples into an one-level list. If value is not a list/tuple, it is converted to an one-item list. For example, (1, 2, [3, 4, ('56', '7')]) is converted to [1, 2, 3, 4, '56', '7']; 1 is converted to [1]. """ if isinstance(value, (list, tuple)): result = [] for item in value: result.extend(Flatten(item)) return result return [value]
def boolean(value): """Parse the string "true" or "false" as a boolean (case insensitive)""" value = value.lower() if value == 'true': return True if value == 'false': return False raise ValueError("Invalid literal for boolean(): {}".format(value))
def has_read_perm(user, group, is_member, is_private): """ Return True if the user has permission to *read* Articles, False otherwise. """ if (group is None) or (is_member is None) or is_member(user, group): return True if (is_private is not None) and is_private(group): return False return True
def max_profit_naive(prices): """ :type prices: List[int] :rtype: int """ max_so_far = 0 for i in range(0, len(prices) - 1): for j in range(i + 1, len(prices)): max_so_far = max(max_so_far, prices[j] - prices[i]) return max_so_far
def levain_flour_weight(recipe, total_weight): """ Figure out the weight of flour in the levain from the total weight. """ total_liquid = sum(recipe["liquid"][i] for i in recipe["liquid"]) flour = total_weight / (1 + total_liquid / 100) return flour
def numerise_params(prop_dict): """ Returns drug properties with all qualitative values transformed into numeric values returns: numerically transformed property dictionaries rtype: dict """ clearance_dict = { 'low (< 5.6)': 1, 'medium (5.6-30.5)': 4, 'high (> 30.5)': 7, 'low (< 12)': 1, 'medium (12-44)': 4 } pampa_dict = { 'low': 2.5, 'med2high': 5.5 } drug_properties = prop_dict for k, v in clearance_dict.items(): if k == drug_properties['clearance_mouse']: drug_properties['clearance_mouse'] = v if k == drug_properties['clearance_human']: drug_properties['clearance_human'] = v for k, v in pampa_dict.items(): if k == drug_properties['pampa']: drug_properties['pampa'] = v if k == drug_properties['logd']: drug_properties['logd'] = v return (drug_properties)
def _index_exists(idx_conf, indexes): """ Check if an index for a collection was already created in the database. idx_conf - index config object from a collection schema indexes - result of request to arangodb's /_api/index?collection=coll_name """ for idx in indexes: if idx_conf['fields'] == idx['fields'] and idx_conf['type'] == idx['type']: return True return False
def sequence_class(immutable): """returns a callable class with a conditional expression.""" return tuple if immutable else list # the conditional expression is the same as below: # if immutable: # cls = tuple # else: # cls = list # return cls
def uppercaseFirstHash(data): """ This function takes the inputted data and formats all of the keys to be lowercase with the first letter capitalized. If the input is anything but a dictionary, it simply raises a TypeError. Args: :param data: The data to be reformatted Raises: TypeError when data is not a dict. Returns: dict: The reformatted dictionary """ if(not isinstance(data, dict)): raise TypeError return {k.lower().capitalize(): v for k, v in data.items()}
def rowToCombo(row, columns): """Converts a row to a list of (Attribute, Value) tuples. Args: row: the input row. columns: the columns of the input row. Returns: combo: the list of (Attribute, Value) tuples. """ res = [] for i, c in enumerate(columns): val = str(row[i]) if val != '': res.append((c, val)) combo = sorted(res, key=lambda x: f'{x[0]}:{x[1]}'.lower()) return combo
def _create_weather_key(lat, lng): """ Creates a properly formatted key for storing in a JSON database. Args: lat (string or float) -- latitude component of coordinate lng (string or float) -- longitude component of coordinate Returns: string -- key value """ tmp = "%s,%s" % (lat, lng) return tmp.replace(".", "")
def get_border_bounding_rect(h, w, p1, p2, r): """Get a valid bounding rect in the image with border of specific size. # Arguments h: image max height. w: image max width. p1: start point of rect. p2: end point of rect. r: border radius. # Returns rect coord """ x1, y1, x2, y2 = p1[0], p1[1], p2[0], p2[1] x1 = x1 - r if 0 < x1 - r else 0 y1 = y1 - r if 0 < y1 - r else 0 x2 = x2 + r + 1 if x2 + r + 1 < w else w y2 = y2 + r + 1 if y2 + r + 1 < h else h return x1, y1, x2, y2
def get_dict_query_field(dict_field_name: str, sub_field: str): """Generate django query key for searching a nested json feild""" return dict_field_name + "__" + sub_field.replace(".", "__")
def InterpolateDepths(near_depth, far_depth, num_depths): """Returns num_depths from (far_depth, near_depth), interpolated in inv depth. Args: near_depth: The first depth. far_depth: The last depth. num_depths: The total number of depths to create, include near_depth and far_depth are always included and other depths are interpolated between them, in inverse depth space. Returns: The depths sorted in descending order (so furthest first). This order is useful for back to front compositing. """ inv_near_depth = 1.0 / near_depth inv_far_depth = 1.0 / far_depth depths = [] for i in range(0, num_depths): fraction = float(i) / float(num_depths - 1) inv_depth = inv_far_depth + (inv_near_depth - inv_far_depth) * fraction depths.append(1.0 / inv_depth) return depths
def flatten(xs): """Returns collection [xs] after recursively flattening into a list.""" if isinstance(xs, list) or isinstance(xs, set) or isinstance(xs, tuple): result = [] for x in xs: result += flatten(x) return result else: return [xs]
def reversepath(path): """ This function reverses a path. """ return path[::-1]
def isNumber(s): """ This function takes a string as an argument and tries to parse it to float. If it can, it returns true. Else, it returns false. This will filter elements in the .dat file so that only numbers are included in the returned arrays """ try: float(s) return True except ValueError: return False
def _remove_dead_branch(transitions_list): """ Remove dead branchs inserting a selfloop in every node that has not outgoing links. Example ------- >>> trj = [1,2,3,1,2,3,2,2,4,3,5] >>> tr = pykov.transitions(trj, nsteps=1) >>> tr [(1, 2), (2, 3), (3, 1), (1, 2), (2, 3), (3, 2), (2, 2), (2, 4), (4, 3), (3, 5)] >>> pykov._remove_dead_branch(tr) >>> tr [(1, 2), (2, 3), (3, 1), (1, 2), (2, 3), (3, 2), (2, 2), (2, 4), (4, 3), (3, 5), (5, 5)] """ head_set = set() tail_set = set() for step in transitions_list: head_set.add(step[1]) tail_set.add(step[0]) for head in head_set: if head not in tail_set: transitions_list.append((head, head)) return None
def decode_pdf_string(bytestring): """ PDF Strings can sometimes be UTF-16. Detect and convert if necessary """ if(bytestring.startswith(b'\xfe\xff') or bytestring.startswith(b'\xff\xfe')): string = bytestring.decode("utf-16") else: string = bytestring.decode("ascii") return(string)
def _fmt_msg(msg): """Format the message for final display. Parameters ---------- msg : str The message to show to the user to provide additional context. returns ------- fmtd : str The formatted message to put into the error message. """ if not msg: return '' return msg + '\n'
def display_body(body_list): """ Sets the body for the message to be displayed with display()\n The body needs to be a list with each element of the list being a line. """ global body if type(body_list) == type(['hey', 'hey']): body = body_list return body elif type(body_list) == type('Hey hey'): body = [body_list] return body else: return f'Error: non supported argument type {type(body_list)}'
def split_layouts_by_arrow(s: str) -> tuple: """ Splits a layout string by first arrow (->). :param s: string to split :return: tuple containing source and target layouts """ arrow = s.find('->') if arrow != -1: source_layout = s[:arrow] target_layout = s[arrow + 2:] if source_layout == '': source_layout = None if target_layout == '': target_layout = None return source_layout, target_layout else: return s, None
def get_file_contents(filepath): """Returns the contents of a file as a string.""" data = "" try: with open(filepath, "r") as open_file: data = open_file.read() except Exception as e: print(e) finally: return data
def _pprint_version(value): """Pretty-print version tuple; takes a tuple of field numbers / values, and returns it as a string joined by dots with a 'v' prepended. """ return "v%s.x" % (".".join(map(str, value)),)
def is_pythagorean_triple(a: int, b: int, c: int) -> bool: """ This function checks the input a, b, c to see whether they satisfy the equation a^2 + b^2 = c^2 """ return True if (a**2 + b**2) == c**2 else False
def dissect_time(sec): """changes total seconds into hours, minutes, seconds""" seconds = sec % 60 minutes = (sec // 60) % 60 hours = (sec // 60) // 60 return hours, minutes, seconds
def parse_ID(seq): """Return the EC number inside the input string. Example ------- "ID\t1.1.1.1\n*****************\n" -> "1.1.1.1" """ seq = seq.split("\n")[0] return seq[2:].strip()
def json_path(path, data): """Extract property by path""" fragments = path.split(".") src = data for p in fragments: src = src[int(p)] if (isinstance(src, list) and p.isdigit()) \ else src[p] return src
def quote_sh_value(value): """quote a string value for use in sh config. """ if not value: return u'' value = u"%s" % (value,) return u'"%s"' % (value.replace('"', '\"'))
def base (t): """ find basic form of word """ return str("".join(sorted(t)))
def _find_method(obj, string): """Find methods in object that starts with `string`. """ out = [] for key in dir(obj): if key.startswith(string): out.append(getattr(obj, key)) return out
def indexByIdMap(cfg): """ Function that returns the dictionary that returns the index of a certain node given the ID. """ return {cfg['nodes'][i]['id']:i for i in range(len(cfg['nodes']))}
def generate_latex_error(error_msg): """ generate_latex_error(error_msg: str) -> str this generates a piece of latex code with an error message. """ s = """\\PackageError{vistrails}{ An error occurred when executing vistrails. \\MessageBreak %s }{vistrails}""" % error_msg return s
def decode_gcs_url(url): """Decode GCS URL. Args: url (str): GCS URL. Returns: tuple: (bucket_name, file_path) """ split_url = url.split('/') bucket_name = split_url[2] file_path = '/'.join(split_url[3:]) return (bucket_name, file_path)