content
stringlengths
42
6.51k
def escape_null(s: str) -> str: """Replaces each null character (\\0) in the input with \\\\0""" return s.replace("\0", "\\0")
def format_pos(pos): """ >>> print(format_pos({'line': 5, 'character': 0})) 6.1 """ return '{}.{}'.format(pos['line'] + 1, pos['character'] + 1)
def getBandIdFromBandPath(bandPath): """Obtains an image band id from its path""" return bandPath[-6:-4]
def time_rep_song_to_16th_note_grid(time_rep_song): """ Transform the time_rep_song into an array of 16th note with pitches in the onsets [[60,4],[62,2],[60,2]] -> [60,0,0,0,62,0,60,0] """ grid_16th = [] for pair_p_t in time_rep_song: grid_16th.extend([pair_p_t[0]] + [0 for _ in range(pair_p_t[1]-1)]) return grid_16th
def contains_a_letter(word): """Helper for :meth:`analyze`""" for char in word: if char.isalpha(): return True return False
def unflatten_dict(dic: dict, sep=".") -> dict: """ Invert the effect of :func:`flatten_dict` """ items = list(dic.items()) items.reverse() out = {} while items: k, v = items.pop() *keys, last_key = k.split(sep) d = out for k in keys: d = d.setdefault(k, {}) d[last_key] = v return out
def extend_slice(slice_name, slices, template_size, target_result): """ Extend slice """ ext_obj = {"name": "Empty", "score": 0.0} extended_list = [ext_obj] * template_size el = extended_list for slice in slices: if slice["name"] == slice_name: print("Slice:", slice_name) for i, n in enumerate( slice["template_slice"] ): # "template_slice":[1, 2, 3, 4] pos = n - 1 el = el[:pos] + [target_result[i]] + el[pos + 1 :] return el
def _get_mappings(files, label, go_prefix): """For a set of files that belong to the given context label, create a mapping to the given prefix.""" mappings = {} for file in files: src = file.short_path #print("mapping file short path: %s" % src) # File in an external repo looks like: # '../WORKSPACE/SHORT_PATH'. We want just the SHORT_PATH. if src.startswith("../"): parts = src.split("/") src = "/".join(parts[2:]) dst = [go_prefix] if label.package: dst.append(label.package) name_parts = label.name.split(".") # special case to elide last part if the name is # 'go_default_library.pb' if name_parts[0] != "go_default_library": dst.append(name_parts[0]) mappings[src] = "/".join(dst) return mappings
def get_cache_encrypt_key(key): """Prepare key for use with crypto libs. :param key: Passphrase used for encryption. """ key += (16 - (len(key) % 16)) * '-' return key.encode('utf-8')
def bits2human(n, format="%(value).1f%(symbol)s"): """Converts n bits to a human readable format. >>> bits2human(8191) '1023.9B' >>> bits2human(8192) '1.0KiB' """ symbols = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB') prefix = {} prefix['B'] = 8 for i, s in enumerate(symbols[1:]): prefix[s] = 1024**(i + 1) * 8 for symbol in reversed(symbols): if n >= prefix[symbol]: value = float(n) / prefix[symbol] return format % locals() return format % dict(symbol=symbols[0], value=n)
def _cons1_111(m1, L11, d_p2p, keff, Cp): """dz constraint for interior sc touching 3 interior sc""" return m1 * Cp * L11 / 3 / d_p2p / keff
def is_readonly_property(cls, name): """Tell whether a attribute can't be setattr'ed.""" attr = getattr(cls, name, None) return attr and isinstance(attr, property) and not attr.fset
def is_listing(op): """Tell if given parameter is a listing.""" return isinstance(op, (list, tuple))
def calc_clust_similarity(target_size, clust_size): """ Linear function to calculate how close the size of the cluster is to the real epileptogenic cluster that we want to find """ if clust_size > target_size: if clust_size >= 2*target_size: clust_size = 0 else: clust_size = target_size - (clust_size - target_size) return (clust_size/target_size)
def get_iou(bb1, bb2): """ Calculate the Intersection over Union (IoU) of two bounding boxes. Parameters ---------- bb1 : dict Keys: {'x1', 'x2', 'y1', 'y2'} The (x1, y1) position is at the top left corner, the (x2, y2) position is at the bottom right corner bb2 : dict Keys: {'x1', 'x2', 'y1', 'y2'} The (x, y) position is at the top left corner, the (x2, y2) position is at the bottom right corner Returns ------- float in [0, 1] """ assert bb1['x1'] <= bb1['x2'] assert bb1['y1'] <= bb1['y2'] assert bb2['x1'] <= bb2['x2'] assert bb2['y1'] <= bb2['y2'] # determine the coordinates of the intersection rectangle x_left = max(bb1['x1'], bb2['x1']) y_top = max(bb1['y1'], bb2['y1']) x_right = min(bb1['x2'], bb2['x2']) y_bottom = min(bb1['y2'], bb2['y2']) if x_right < x_left or y_bottom < y_top: return 0.0 # The intersection of two axis-aligned bounding boxes is always an # axis-aligned bounding box intersection_area = (x_right - x_left) * (y_bottom - y_top) # compute the area of both AABBs bb1_area = (bb1['x2'] - bb1['x1']) * (bb1['y2'] - bb1['y1']) bb2_area = (bb2['x2'] - bb2['x1']) * (bb2['y2'] - bb2['y1']) # compute the intersection over union by taking the intersection # area and dividing it by the sum of prediction + ground-truth # areas - the interesection area iou = intersection_area / float(bb1_area + bb2_area - intersection_area) assert iou >= 0.0 assert iou <= 1.0 return iou
def map_currency(currency, currency_map): """ Returns the currency symbol as specified by the exchange API docs. NOTE: Some exchanges (kraken) use different naming conventions. (e.g. BTC->XBT) """ if currency not in currency_map.keys(): return currency return currency_map[currency]
def unquote_header_value(value): """Unquotes a header value. This does not use the real unquoting but what browsers are actually using for quoting. :param value: the header value to unquote. """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the # RFC is met will result in bugs with internet explorer and # probably some other browsers as well. IE for example is # uploading files with "C:\foo\bar.txt" as filename value = value[1:-1] return value
def _as_graph_element(obj): """Convert `obj` to a graph element if possible, otherwise return `None`. Args: obj: Object to convert. Returns: The result of `obj._as_graph_element()` if that method is available; otherwise `None`. """ conv_fn = getattr(obj, "_as_graph_element", None) if conv_fn and callable(conv_fn): return conv_fn() return None
def expand_tcp_flags(flag_code): """ Convert a one character tcp flag to a three character tcp flag """ retval="" for character in flag_code: if character=="S": retval=retval+" SYN" elif character=="P": retval=retval+" PSH" elif character=="F": retval=retval+" FIN" elif character=="C": retval=retval+" CWR" elif character=="R": retval=retval+" RST" elif character=="U": retval=retval+" URG" elif character=="E": retval=retval+" ECE" elif character=="A": retval=retval+" ACK" else: retval=retval=character retval=retval.strip() return retval
def make_shell_filestats_url(host: str, shell_port: int, path: str) -> str: """ Make the url for filestats data in heron-shell from the info stored in stmgr. """ return f"http://{host}:{shell_port}/filestats/{path}"
def swap(a_list, index1, index2): """assumes a_list is a list, assumes index1 is an int representing the index of one of the two values to be swaped assumes index1 is an int representing the index of one of the two values to be swaped does not modify the inputed list returns a list, equivalent to a_list with index1 and index2 swapped e.g. swap(['a','b','c'], 0, 2) -> ['c','b','a'] """ b_list = a_list.copy() b_list[index1] = a_list[index2] b_list[index2] = a_list[index1] return b_list
def palindrome(string): """palindrome (string) - returns a boolean value for whether the parameter string is a palindrome""" if str(string) == str(string)[::-1]: return True else: return False
def puzzle_input(daynumber): """ return the open file for given day """ filename = f"puzzle_inputs/{daynumber}.txt" try: return open(filename) except FileNotFoundError: print(f"Oops - couldn't find '{filename}'")
def extract_properties_when_schemaless(group_objects_list): """ If your Active Directory schema does not natively support Unix account attributes and a schema extension is not possible, Safeguard Authentication Services uses "schemaless" functionality where Unix account information is stored in the altSecurityIdentities attribute. Examples of group_object in schemaless mode: { "DistinguishedName": "CN=tg-1974,CN=Users,DC=d16,DC=sb", "Name": "tg-1974", "ObjectClass": "group", "ObjectGUID": "ee3b40d7-3419-45cc-8778-d90fd798ae2d", "altSecurityIdentities": [ "X509:<S>CN=Posix Group<I>CN=Quest Software<DATA>GroupName: tg-1974", "X509:<S>CN=Posix Group<I>CN=Quest Software<DATA>GroupGidNumber: 8135" ] }, { "DistinguishedName": "CN=tg-1993,CN=Users,DC=d16,DC=sb", "Name": "tg-1993", "ObjectClass": "group", "ObjectGUID": "1a7de3d9-d8ff-477b-8498-05ce330f9e11", "altSecurityIdentities": [ "X509:<S>CN=Posix Group<I>CN=Quest Software<DATA>GroupName: tg-1993", "X509:<S>CN=Posix Group<I>CN=Quest Software<DATA>GroupGidNumber: 8136" ] } """ attrs = ['GroupName', 'GroupGidNumber'] groups = [] for group_object in group_objects_list: group = [] for attr in attrs: alt_sec_ids = group_object['altSecurityIdentities'] for alt_sec_id in alt_sec_ids: label = 'X509:<S>CN=Posix Group<I>CN=Quest Software<DATA>' + attr + ':' if label in alt_sec_id: group.append(alt_sec_id[len(label):].strip()) break else: group.append('') # A Group object is considered to be 'Unix-enabled' if it has values for # the Group GID Number and Group Name. if group[0] and group[1]: dn = 'DistinguishedName' if dn in group_object and group_object[dn]: group.insert(0, group_object[dn]) else: group.insert(0, '') groups.append(group) return groups
def cleanup_description(desc): """Clean up a multiline description.""" return " ".join(desc.replace('\n', ' ').replace('\r', ' ').split())
def quick_one(lis): """ the first item of the list is the key, all items that are less than the key will be on the left of the key, all items that are larger will be on the right of the key, returns the list and the index of the key. """ nList = lis.copy() key = lis[0] keyI = 0 pMin = 0 pMax = len(lis)-1 while(pMin!=pMax): while pMax>keyI: if nList[pMax]<=key: nList[pMax],nList[keyI] = nList[keyI],nList[pMax] keyI = pMax break pMax-=1 while pMin<keyI: if nList[pMin]>key: nList[pMin],nList[keyI] = nList[keyI],nList[pMin] keyI = pMin break pMin+=1 return nList,keyI
def hyp2id(hyp, dictionary): """ Converts an hyphen to its respective id in dictionary. :param hyp: a string :param dictionary: a Python dictionary with string as keys and integers as values. :return: an integer """ return dictionary[hyp] if hyp in dictionary else 0
def decode_topic_name(encoded: str) -> str: """ Reverses ``encode_topic_name``. :param encoded: the encoded SNS topic name :return: the decoded channel name """ decoded = encoded decoded = decoded.replace("_WCD_", "*") decoded = decoded.replace("_FWS_", "/") decoded = decoded.replace("_DOT_", ".") decoded = decoded.replace("_COL_", ":") decoded = decoded.replace("_LT_", "<") decoded = decoded.replace("_GT_", ">") return decoded
def enumerate_genes(genes): """Enumerate genes""" schema={} for i,x in enumerate(genes): if x in schema: schema[x].append(i) else: schema[x] = [i] return schema
def distance_helper(initial_velocity, acceleration, time): """ Calculates the distance traveled given the initial velocity, acceleration, and time, Helper function to the distance function. :param initial_velocity: Integer initial velocity :param acceleration: Integer acceleration :param time: Integer time :return: Integer distance traveled """ dist = initial_velocity * time + 0.5 * (acceleration * time ** 2) return dist
def mean(data): """ Return the sample arithmetic mean of data. :param data: list of floats or ints. :return: mean value (float). """ n = len(data) if n < 1: raise ValueError('mean requires at least one data point') # return sum(data)/n # in Python 2 use sum(data)/float(n) return sum(data) / float(n)
def get_tool_names(): """ Returns a list of expected DExTer Tools """ return [ 'clang-opt-bisect', 'help', 'list-debuggers', 'no-tool-', 'run-debugger-internal-', 'test', 'view' ]
def boundMotorSpeed(speed): """ Bound speed to the limits allowed by crickit motor.throttle """ if speed < -1: return -1 if speed > 1: return 1 return speed
def create_deets_message(time, size, image): """Creates message of image details for the GUI client Image details returned include the time the image was uploaded or processed and the image size in pixels. If the image was original, the upload time is returned. If the image was inverted, the processed time is returned. Args: time (str): timestamp of upload/processing size (tuple): width, height of image in pixels image (str): name of image Returns: str: message to be shown to user """ if "inverted" in image: time_type = "processed" else: time_type = "uploaded" width, height = size deets_message = "Time {}: {}\n" \ "Image size: {} x {}" \ .format(time_type, time, width, height) return deets_message
def to_underscore_style(text): """Changes "Something like this" to "something_like_this".""" text = text.lower().replace(" ", "_").replace("-", "_") return "".join(x for x in text if x.isalpha() or x.isdigit() or x == "_")
def column_of(row, col, width=3, height=3, include=True): """Return all coordinates in the column of (col, row) as a list. Args: row (int): The row of the field. col (int): The column of the field. width (int): The width of the sudoku. height (int): The height of the sudoku. include (bool): Whether or not to include (row, col). Returns: list of (int, int): list of pairs (row, column) of all fields in the same column. """ return [(i, col) for i in range(width * height) if include or i != row]
def ee_function_tree(name): """Construct the tree structure based on an Earth Engine function. For example, the function "ee.Algorithms.FMask.matchClouds" will return a list ["ee.Algorithms", "ee.Algorithms.FMask", "ee.Algorithms.FMask.matchClouds"] Args: name (str): The name of the Earth Engine function Returns: list: The list for parent functions. """ func_list = [] try: items = name.split('.') if items[0] == 'ee': for i in range(2, len(items) + 1): func_list.append('.'.join(items[0:i])) else: for i in range(1, len(items) + 1): func_list.append('.'.join(items[0:i])) return func_list except Exception as e: print(e) print('The provided function name is invalid.')
def to_upper(inp): """ Recursively convert inputs to uppercase strings, except if None. Parameters ---------- inp : str or list of str Object to be converted to upper. Returns ------- str, list or None """ if inp is None: return None if isinstance(inp, list): return [to_upper(s) for s in inp] return str(inp).upper()
def get_destroyed_endpoint(vol, array): """Return Destroyed Endpoint or None""" try: return bool(array.get_volume(vol, protocol_endpoint=True, pending=True)['time_remaining'] != '') except Exception: return False
def make_flat(list_of_lists: list) -> list: """ [(1,2), (3,4)] -> [1, 2, 3, 4]""" return sum([list(item) for item in list_of_lists], [])
def incremental_mean_differentSizeBatches(xbarj,Nj,xbarm,Nm): """ Calculates the incremental mean different batch sizes Args: float: xbarj mean of all previous float: Nj number of planets in all previous batches ndarray: xbarm mean of values in current batch float: Nm number of elements in current batch """ xbarjp1 = (Nj*xbarj + Nm*xbarm)/(Nj+Nm) return xbarjp1
def build_problem_report(req_data): """Returns problem report dict from req_data sent by GitHub hook.""" return { "product": "Ports & Packages", "component": "Individual Port(s)", "version": "Latest", "summary": "GitHub Pull Request #{number}: {title}".format( number=req_data['pull_request']['number'], title=req_data['pull_request']['title']), "description": "{description}\nBy: {name}({name_url})".format( description=req_data['pull_request']['body'], name=req_data['pull_request']['user']['login'], name_url=req_data['pull_request']['user']['url']), "url": "{url}".format(url=req_data['pull_request']['html_url']) }
def convert_experience_amount(amount: str) -> tuple: """ convert_experience_amount - Converts a string into a tuple of amount and type Args: amount (str): The string to convert Returns: tuple: Index 0 is the amount and index 1 is the type """ xp_type = "levels" if isinstance(amount, str): amount = amount.lower() if amount.endswith("p"): xp_type = "points" if not amount.isdigit(): amount = amount[:-1] return (amount, xp_type)
def get_ss(ss_string): """ Converts secondary structure string into a list of indices of where secondary structure changes (plus start and end coordinates of the sequence) """ output = [0] for i in range(1,len(ss_string)): if ss_string[i] != ss_string[i-1]: output.append(i) if output[-1] != len(ss_string)-1: output.append(len(ss_string)-1) return output
def print_belief_state_woz_requestables(curr_values, distribution, threshold): """ Returns the top one if it is above threshold. """ requested_slots = [] # now we just print to JSON file: for idx, value in enumerate(curr_values): if distribution[idx] >= threshold: requested_slots.append(value) return requested_slots
def __get_http_methods(tagged_item): """ extracts the http methods for a tagged link or resource decorator :param tagged_item: :return: the list of http methods """ def default_method(args): return ['POST'] if len(args) > 0 else ['GET'] tag_args = tagged_item.get('argspec') http_methods = tagged_item.get('decorator_kwargs').get('method', default_method(tag_args)) if not isinstance(http_methods, list): http_methods = [http_methods] return http_methods
def find(word, letter, start_index): """ Find the index of a letter in a word starting the search at specific index """ index = start_index while index < len(word): if word[index] == letter: return index index += 1 return -1
def _get_folder(gi, folder_name, library, libitems): """Retrieve or create a folder inside the library with the specified name. """ for item in libitems: if item["type"] == "folder" and item["name"] == "/%s" % folder_name: return item return gi.libraries.create_folder(library.id, folder_name)[0]
def listCycle(x, list): """Append x to list and maintain length. Returns updated list.""" list.append(x) # append new value # list.pop(0) # get rid of first value (to maintain size) del list[0] # get rid of first value (to maintain size) return list
def byte_bit_value(byte, schema): """ Extract bit(s) value from a byte. BYTE INDEX = | 0 | 1 | 2 | 3 || 4 | 5 | 6 | 7 | msb lsb 128 1 args: - byte value(int) - data schema(list): [index, bits] - data's starting bit index. - number of bits. returns: int """ index, bits = schema if index < 0 or index > 7: raise ValueError("Schema index must be 0 thru 7") if bits < 1 or bits > 8: raise ValueError("Schema bits must be 1 thru 8") if len( list(bin(byte)[2:]) ) > 8: raise ValueError("Number too big. Not a byte value.") if index == 0 and bits == 8: # nothing to do return byte shift = 8 - (index + bits) mask = 0xFF >> (shift + index) return byte >> shift & mask
def dev_dupe_remover(finals, dupelist): """ Filter dictionary of autoloader entries. :param finals: Dict of URL:content-length pairs. :type finals: dict(str: str) :param dupelist: List of duplicate URLs. :type duplist: list(str) """ for dupe in dupelist: for entry in dupe: if "DevAlpha" in entry: del finals[entry] return finals
def build_network_url_from_gateway_url(gateway_href): """Build network URI for NSX Proxy API. It replaces '/api/edgeGatway/' or '/api/admin/edgeGatway/' with /network/EDGE_ENDPOINT and return the newly formed network URI. param: str gateway_href: gateway URL. for ex: https://x.x.x.x/api/admin/edgeGateway/uuid return network href rtype: str """ _NETWORK_URL = '/network/edges/' _GATEWAY_API_URL = '/api/edgeGateway/' _GATEWAY_ADMIN_API_URL = '/api/admin/edgeGateway/' network_url = gateway_href if gateway_href.find(_GATEWAY_API_URL) > 0 or gateway_href.find( _GATEWAY_ADMIN_API_URL) > 0: network_url = network_url.replace(_GATEWAY_API_URL, _NETWORK_URL) return network_url.replace(_GATEWAY_ADMIN_API_URL, _NETWORK_URL) return None
def split_html(html_string): """ Divides an html document into three seperate strings and returns each of these. The first part is everything up to and including the <body> tag. The next is everything inside of the body tags. The third is everything outside of and including the </body> tag. :type html_string: string :param html_string: html document in string form :returns: three strings start, body, and ending """ try: i = html_string.index("<body") j = html_string.index(">", i) + 1 k = html_string.index("</body") except ValueError: raise Exception("This is not a full html document.") start = html_string[:j] body = html_string[j:k] ending = html_string[k:] return start, body, ending
def tostr(input_string): """ Change a list of strings into a multiline string """ if isinstance(input_string, list): return '\n'.join([tostr(i) for i in input_string]) else: return str(input_string)
def compare(first, second): """Compares the two types for equivalence. If a type composes another model types, .__dict__ recurse on those and compares again on those dict values """ if not hasattr(second, '__dict__'): return False # Ignore any '_raw' keys def norm_dict(d): return dict((k, d[k]) for k in d if k != '_raw') return norm_dict(first.__dict__) == norm_dict(second.__dict__)
def pixel_scale_interpolation_grid_tag_from_pixel_scale_interpolation_grid( pixel_scale_interpolation_grid ): """Generate an interpolation pixel scale tag, to customize phase names based on the resolution of the interpolation \ grid that deflection angles are computed on before interpolating to the and sub aa. This changes the phase name 'phase_name' as follows: pixel_scale_interpolation_grid = 1 -> phase_name pixel_scale_interpolation_grid = 2 -> phase_name_pixel_scale_interpolation_grid_2 pixel_scale_interpolation_grid = 2 -> phase_name_pixel_scale_interpolation_grid_2 """ if pixel_scale_interpolation_grid is None: return "" else: return "__interp_{0:.3f}".format(pixel_scale_interpolation_grid)
def importAny(*modules): """ Import by name, providing multiple alternative names Common use case: Support all the different package names found between 2.0 add-ons, 2.1 AnkiWeb releases, and 2.1 dev releases Raises: ImportError -- Module not found Returns: module -- Imported python module """ for mod in modules: try: return __import__(mod) except ImportError: pass raise ImportError("Requires one of " + ', '.join(modules))
def buy_date_adaptor(buy_date: str): """ 20200101 -> 2020-01-01 :param buy_date: :return: """ if len(buy_date) == 8: buy_date = f'{buy_date[:4]}-{buy_date[4:-2]}-{buy_date[-2:]}' return buy_date
def subtract(a, b): """Subtract two numbers and return the difference""" difference = round(a-b, 4) print("The difference of " + str(a) + " and " + str(b) + " is " + str(difference) + ".") return str(a) + " - " + str(b) + " = " + str(difference)
def add_to_tracking_totals(totals, item): """ Adds totals from item to totals :param dict totals: Totals to be added to :param dict item: Item to be added to totals dict :return: totals dict :rtype: dict """ for key, value in item.items(): if ( type(value) is int and key not in ["GP", "W", "L", "TEAM_ID", "PLAYER_ID"] ) or key in [ "MIN", "DIST_MILES", "DIST_MILES_OFF", "DIST_MILES_DEF", "TIME_OF_POSS", ]: if value is not None: totals[key] = totals.get(key, 0) + value return totals
def transcript(cloud_response): """Get text transcription with the highest confidence from the response from google cloud speech-to-text service. Args: cloud_response: response from speech-to-text service Returns: (transcription, confidence): string value of transcription with corresponding confidence score """ transcription = None confidence = 0.0 try: for result in cloud_response.results: for alt in result.alternatives: if confidence < alt.confidence: confidence = alt.confidence transcription = alt.transcript except: pass return (transcription, confidence)
def scaleFromRedshift(redshift): """ Converts a redshift to a scale factor. :param redshift: redshift of the object :type redshift: float or ndarray :return: scale factor :rtype: float or ndarray """ return 1. / (redshift + 1.)
def feature_pairs(f): """Expand features to include pairs of features where one is always a f=v feature.""" pairs = [x + ".x." + y for x in f for y in f if u'=' in y] return pairs + f
def cleanObject(obj,dimensions): """ Get only the variables required to netcdf2d Parameters ---------- obj:object dimensions=list,['nnode','ntime'] Notes ----- idimensions=['inode','itime'] """ if not 'variable' in obj:raise Exception("Add {} to the default parameter object".format('variable')) _obj={} idimensions = ["{}{}".format('i',dimension[1:]) for dimension in dimensions] for name in idimensions: if name in obj: _obj[name]=obj[name] _obj['variable']=obj['variable'] return _obj
def getshapesidedict() -> dict: """Returns a dictionary of side or polygon definitions for simple solids Returns: dictionary of side or polygon definitions for basic solids """ return {"tetrahedra":((2, 1, 0), (2, 3, 1), (0, 3, 2), (3, 0, 1)), "cube":((1, 2, 3, 0), (5, 6, 7, 4), (0, 3, 6, 5), (4, 7, 2, 1), (4, 1, 0, 5), (2, 7, 6, 3)), "hexahedra":((2, 3, 1), (0, 3, 2), (3, 0, 1), (1, 4, 2), (2, 4, 0), (1, 0, 4)), "octahedra":((1, 2, 0), (4, 1, 0), (3, 4, 0), (2, 3, 0), (2, 1, 5), (1, 4, 5), (4, 3, 5), (3, 2, 5))}
def serialize_for_deletion(elasticsearch_object_id): """ Serialize content for bulk deletion API request Args: elasticsearch_object_id (string): Elasticsearch object id Returns: dict: the object deletion data """ return {"_id": elasticsearch_object_id, "_op_type": "delete"}
def maybe_flip_x_across_antimeridian(x: float) -> float: """Flips a longitude across the antimeridian if needed.""" if x > 90: return (-180 * 2) + x else: return x
def date_group(date): """date_group(date) Converts a date string into a year/season ID tuple. Positional arguments: date (str) - date string, in "MM/DD/YYYY" format Returns: (tuple) - tuple with 2-digit year and season ID (0 for Su, 1 for Fa, 2 for Sp) The cutoffs for Fall, Spring, and Summer are: Jan-May: Summer June-August: Fall September-December: (next) Spring """ # Gather month, day, and year parts = date.split('/') if len(parts) != 3: raise ValueError('date string must be in "MM/DD/YYYY" format') m = int(parts[0]) d = int(parts[1]) y = int(parts[2]) # Use month and day to determine season if m <= 5: return (y % 100, 0) elif m <= 8: return (y % 100, 1) else: return ((y + 1) % 100, 2)
def format_config_parameter(config_parameter, language): """ Format the name of config parameter, adding the target language of necessary. :param config_parameter: Name of config parameter. :type config_parameter: str :param language: Pipeline language. :type language: str :return: Formatted config parameter. :rtype: str """ if "{language}" in config_parameter: return config_parameter.format(language=language.upper()) return config_parameter
def rdict(x): """ recursive conversion to dictionary converts objects in list members to dictionary recursively """ if isinstance(x, list): l = [rdict(_) for _ in x] return l elif isinstance(x, dict): x2 = {} for k, v in x.items(): x2[k] = rdict(v) return x2 else: if hasattr(x, '__dict__'): d = x.__dict__ toremove = [] for k, v in d.items(): if v is None: toremove.append(k) else: d[k] = rdict(v) for k in toremove: del(d[k]) return d else: return x
def decode_to_string(data: str or bytes) -> str: """ Simple helper function that ensures that data is decoded from `bytes` with `UTF-8` encoding scheme :param data: takes in both `str` or `bytes` object; represents any type of string or bytes object :return: string object """ return data if isinstance(data, str) else data.decode('utf-8')
def _opt_var_str(name): """Puts an asterisk superscript on a string.""" return '{}^*'.format(name)
def parents_at_rank(graph, root, parent_rank): """ loop through graph from root taxon, assigning leaf nodes to parent nodes at a given rank. """ parents = {} def descend(root, parent): """ Iteratively descend from a root to generate a set of taxids unless the child taxid is in the list of taxids to mask. """ if root in graph: for child, rank in graph[root].items(): if rank == parent_rank: descend(child, child) elif parent: parents[child] = parent descend(child, parent) else: descend(child, None) descend(str(root), str(root)) return parents
def get_media_stream(streams): """Returns the metadata for the media stream in an MXF file, discarding data streams.""" found = None for stream in streams: # skip 'data' streams that provide info about related mxf files if stream['codec_type'] == 'data': continue if stream['codec_type'] == 'audio': continue if found: raise UserWarning('Expected only one media stream per MXF.') found = stream return found
def check_header(line): """ Check whether a line is header, if it is, change it into html format :param line: str, a line in markdown file :return: boolean, whether a line is header str, the line in html format """ header_id = line.replace(' ', '-') if line[:7] == '###### ': line = '<h6 id="' + header_id[7:] + '">' + line[7:] + '</h6>' elif line[:6] == '##### ': line = '<h5 id="' + header_id[6:] + '">' + line[6:] + '</h5>' elif line[:5] == '#### ': line = '<h4 id="' + header_id[5:] + '">' + line[5:] + '</h4>' elif line[:4] == '### ': line = '<h3 id="' + header_id[4:] + '">' + line[4:] + '</h3>' elif line[:3] == '## ': line = '<h2 id="' + header_id[3:] + '">' + line[3:] + '</h2>' elif line[:2] == '# ': line = '<h1 id="' + header_id[2:] + '">' + line[2:] + '</h1>' else: return False, '' return True, line
def translate_inequality(param_name): """ Replace GT or LT at the end of a param name by '>' or '<' to achieve Twilio-like inequalities. """ for suffix, replacement in (('GT', '>'), ('LT', '<')): if param_name.endswith(suffix): return param_name[:-len(suffix)] + replacement return param_name
def bin2state(bin, num_bins, limits): """ :param bin: index in the discretization :param num_bins: the total number of bins in the discretization :param limits: 2 x d ndarray, where row[0] is a row vector of the lower limit of each discrete dimension, and row[1] are corresponding upper limits. .. note:: This is the inverse of state2bin function. Given an index ``bin``, the number of the bins ``num_bins``, and the limits on a single state dimension, this function returns the corresponding value in the middle of the bin (ie, the average of the discretizations around it) """ bin_width = (limits[1] - limits[0]) / num_bins return bin * bin_width + bin_width / 2 + limits[0]
def handle_single_ddc(data): """ produces a about node based on DDC """ return {"identifier": {"@type": "PropertyValue", "propertyID": "DDC", "value": data}, "@id": "http://purl.org/NET/decimalised#c"+data[:3]}
def hello(who): """Say hello to somebody. - who: the person to say hello to.""" return "Hello %s!" % who
def x_range(x): """Difference between maximum and minimum.""" return max(x) - min(x)
def real_number(std_num: float) -> float: """Get the real value of the standard number. Args: std_num: The number you want to reduction. Returns: The real value of the number. """ return float(std_num) / 100000000
def all_equal(values: list): """Check that all values in given list are equal""" return all(values[0] == v for v in values)
def NearestIndex( vector, value, noPrint=False, debug=False ): """Returns nearest two indices which bracket a specified value in a vector. Given an input list or numpy 1-D array, which is asumed to be monotonically increasing or decreasing, find the indices of the two points with values closest to parameter 'value'. Parameters ---------- vector : sequence (list, tuple, numpy.ndarray) of float value : float noPrint : bool, optional if True, suppresses printout [default = False] debug : bool, optional if True, prints extra debugging info Returns ------- (i1, i2) : tuple of (int, int) tuple of indices for vector which bracket input value """ npts = len(vector) if (value < min(vector)) or (value > max(vector)): if noPrint: return (None, None) else: msg = " value {0} lies outside range of input vector ({1} to {2})!".format(value, min(vector), max(vector)) print(msg) return None diff1 = vector[1] - vector[0] if diff1 > 0: # vector is increasing Sign = 1 else: # vector is decreasing Sign = -1 i1 = i2 = 0 diff = Sign*(value - vector[0]) if debug: print(diff) for i in range(1, npts): newdiff = Sign*(value - vector[i]) if debug: print(i, newdiff) if (newdiff > 0) and (newdiff <= diff): diff = newdiff i1 = i else: # we just crossed over i2 = i break if noPrint is False: print(" input_vector[{0},{1}] = {2}, {3}".format(i1, i2, vector[i1], vector[i2])) return (i1, i2)
def feedforward(input, layers): """Compute and return the forward activation of each layer in layers.""" activations = [input] X = input for layer in layers: Y = layer.forward(X) #feed the input into the layer activations.append(Y) X = Y #use the current output as the input for the next layer return activations
def populate_candidates(data): """Process orig_data and add any ext_id matches as candidates.""" candidates = {} for entry in data.values(): if not entry.get('ext_ids'): continue base_info = { 'orig_photo_id': entry.get('photo_id'), 'orig_long_id': '{}/{}'.format( entry.get('museum_obj'), entry.get('db_id')), # needed? 'dupe_photo_id': None, # needed? 'dupe_long_id': None # needed? } for ext_id in entry.get('ext_ids'): candidates[ext_id] = base_info.copy() candidates[ext_id]['dupe_long_id'] = ext_id return candidates
def extract_name_angle(line): """ extract name in <> """ idx1 = line.find('<') idx2 = line.find('>') name = line[idx1+1:idx2] return name
def nested_get(ind, coll, lazy=False): """ Get nested index from collection Examples -------- >>> nested_get(1, 'abc') 'b' >>> nested_get([1, 0], 'abc') ['b', 'a'] >>> nested_get([[1, 0], [0, 1]], 'abc') [['b', 'a'], ['a', 'b']] """ if isinstance(ind, list): if lazy: return (nested_get(i, coll, lazy=lazy) for i in ind) else: return [nested_get(i, coll, lazy=lazy) for i in ind] return seq else: return coll[ind]
def remove_arr_elements(arr_element, count): """ Remove the elements from object_state_arr """ for _ in range(count): arr_element.pop() return arr_element
def check_issubset(to_check, original): """ Check that contain of iterable ``to_check`` is among iterable ``original``. :param to_check: Iterable with elements to check. :param original: Iterable with elements to check to. :return: Boolean. """ s = set() # Need this because ``set`` remove double letters like ``RR`` for item in to_check: s.add(item) return s.issubset(original)
def counter_value(path): """ Converts a zookeeper path with a counter into an integer of that counter :param path: a zookeeper path :rtype: the integer encoded in the last 10 characters. """ return int(path[-10:])
def center(numpoints, refcoords): """ Center a molecule using equally weighted points Parameters numpoints: Number of points refcoords: List of reference coordinates, with each set a list of form [x,y,z] (list) Returns refcenter: Center of the set of points (list) relcoords: Moved refcoords relative to refcenter (list) """ refcenter = [] relcoords = [] for i in range(3): refcenter.append(0.0) for i in range(numpoints): refcenter[0] += refcoords[i][0] refcenter[1] += refcoords[i][1] refcenter[2] += refcoords[i][2] for i in range(3): refcenter[i] = refcenter[i] / numpoints for i in range(numpoints): relcoords.append([]) relcoords[i].append(refcoords[i][0] - refcenter[0]) relcoords[i].append(refcoords[i][1] - refcenter[1]) relcoords[i].append(refcoords[i][2] - refcenter[2]) return refcenter, relcoords
def wgtd_avg(lines): """ Returns the weighted average of a set of line coefficients """ avg_coeffs = [0,0,0] i = 0 n = len(lines) # Weighted average of line coefficients to get smoothed lane lines for line in lines: i += 1 avg_coeffs = avg_coeffs + (i * line.coeffs / ((n**2 + n) / 2)) return avg_coeffs
def is_search(splunk_record_key): """Return True if the given string is a search key. :param splunk_record key: The string to check :type splunk_record_key: str :rtype: bool """ return splunk_record_key == 'search'
def get_hyperlink(path): """Convert file path into clickable form.""" text = "Click to open in new tab" # convert the url into link return f'<a href="{path}" target="_blank">{text}</a>'
def resolve_cyvcf2_genotype(cyvcf2_gt): """ Given a genotype given by cyvcf2, translate this to a valid genotype string. Args: cyvcf2_gt (cyvcf2.variant.genotypes) Returns: genotype (str) """ if cyvcf2_gt[2]: separator = "|" else: separator = "/" if cyvcf2_gt[0] == -1: a_1 = "." else: a_1 = str(cyvcf2_gt[0]) if cyvcf2_gt[1] == -1: a_2 = "." else: a_2 = str(cyvcf2_gt[1]) genotype = a_1 + separator + a_2 return genotype
def insertion_sort(arr, simulation=False): """Insertion Sort Complexity: O(n^2) """ for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cursor: # Swap the number down the list arr[pos] = arr[pos - 1] pos = pos - 1 # Break and do the final swap arr[pos] = cursor return arr
def join_image_tag(image, tag): """ Join an image name and tag. """ if not tag: return image return ':'.join((image, tag))
def bubble_sort(x): """return a sorted copy of the input list x""" L = x[:] swap = False while not swap: swap = True print(L) for i in range(1,len(L)): if L[i] < L[i-1]: swap = False L[i-1], L[i] = L[i], L[i-1] return L
def to_megabytes_factor(unit): """Gets the factor to turn kb/gb into mb""" lower = unit.lower() if lower == 'gb': return 1000 if lower == 'kb': return 0.001 return 1
def fibonacci(n): """ Time complexity: O(n) Space complexity: O(n) Pro: keeps backlog of calculated terms and if the function is called repeatedly on the same number it will run in O(1) Con: O(n) space and O(2n) running time in the general case """ if not hasattr(fibonacci, "memory"): fibonacci.memory = {} if n == 0 or n == 1: return 1 elif n in fibonacci.memory: return fibonacci.memory[n] else: next = fibonacci(n - 1) + fibonacci(n - 2) fibonacci.memory[n] = next return next