content
stringlengths
42
6.51k
def get_minibatch_blob_names(is_training=True): """Return blob names in the order in which they are read by the data loader. """ # data blob: holds a batch of N images, each with 3 channels blob_names = ['data', 'rois', 'labels'] return blob_names
def key2param(key): """ max-results -> max_results """ result = [] key = list(key) if not key[0].isalpha(): result.append('x') for c in key: if c.isalnum(): result.append(c) else: result.append('_') return ''.join(result)
def parse_odbc(url): """ Parse Redshift ODBC URL ----------------------- :param url: Fully Qualified ODBC URL :type url: str :return parsed: ODBC fields parsed into respective fields. :rtype parsed: dict .. example:: Driver={Amazon Redshift (x64)}; Server=server_name...
def is_quote(string: str, quote_index: int, is_looking_for_opening: bool) -> bool: """ indicates whether the quote str[quote_index] is an opening/closing quote :param string: the character string where the quote is located :param quote_index: the index of the quote in string :param is_looking_for_o...
def simple_div(n): """ Calculate the divisors of n. Used to split arrays into a groups of integer size, or to asses how large the batch size should be when training a model :param n: :return: """ return [i for i in range(n, 0, -1) if n % i == 0]
def handle_api_error(e): """Returns 500 internal server error when Giphy API doesn't respond successfully. """ return f"Failed to call Giphy API: {e}", 500
def _inversion_simple(a3, a0): """Solve for degree 5 polynomial with coefficients a5=1, a3=0., a0.""" return (-a0)**(1./5.)
def funded_by_grant(paper, grant_id): """ Determine whether the paper was funded by the specified grant, and if specified, the rationale behind how the paper aligns with the grant. Parameters ---------- paper : dict The 'paper' entry from the papers.yaml database. grant_id : str ...
def str_to_bool(string_in: str): """convert a string to boolean Args: string_in (string): Text from config file value Raises: ValueError: Cannot convert the string to a bool as it isn't True or False Returns: Boolean: True/False value """ if string_in.lower() == "true"...
def get_dict_buildin(dict_obj, _type=(int, float, bool, str, list, tuple, set, dict)): """ get a dictionary from value, ignore non-buildin object """ non_buildin = {key for key in dict_obj if not isinstance(dict_obj[key], _type)} return dict_obj if not non_buildin else {key: dict_obj[key] for key in...
def all_groups_completed(groups): """Returns groups if they are all completed, otherwise False.""" if all(len(g.get('jobs')) == g.get('completed') for g in groups): return groups else: return False
def pyAttrName2XmlAttrName(key): """ The @pyAttrName2XmlAttrName@ converts the Python XML attribute name @key@ to an appropriate XML attribute identifier. If the *key* is 'cssClass' then it is translated into 'class'. If an HTML5 attribute *data_xxxx* is used, then change that to *data-xxxx*. ""...
def interpolate_value_from_list_of_dicts(value1, tag_of_val1, list_of_dicts, tag_of_result): """ returns the linear interpolation of y-value for x-value of 'value1' assumptions are: - x-values are saved with the tag 'tag_of_val1' - y-values are saved with the tag 'tag_of_result' ...
def is_non_strict_type(type1, compare_type): """ Returns true if the given type is the same as a comparison type but does it less rigorous than issubclass(). The main advantage is that classes of modules which where reloaded during runtime are still recognized. WARNING: If the name of a class in a diffe...
def find_in_list_by_condition(search_key_value_pairs, search_list): """Find one item that match given search key value pairs. :param search_key_value_pairs: dictionary that contains search key and values :param search_list: list of dictionary objects to search :return: a single item that matches cr...
def str2int(name): """Convert well address into a row-major index.""" row = ord(name[0].upper()) - 65 col = int(name[1:]) - 1 assert 0 <= row < 8, 'Invalid well address "%s"' % name assert 0 <= col < 12, 'Invalid well address "%s"' % name return row*12 + col
def writefile(filename, contents): """ Write File This function will write, and if it does not exist create the given file. It will fill the file with the content array. """ result = True try: outfile = open(filename,'w') outfile.writelines(contents) outfile.flush() outfile.close() except IOError as ...
def _extent(x, y): """Get data extent for pyplot imshow. Parameters ---------- x: list Data array on X-axis. y: list Data array on Y-axis. Returns ------- [float, float, float, float] X and Y extent. """ dx, dy = .5 * (x[1] - x[0]), .5 * (y[1] - y[0]) ...
def calculate_brightness(brightness=1, color_code=[255, 255, 255]): """Given a color code (array of three int where 0 =< int =< 255), we put the brightness multiplicator on it""" return [round(nb * brightness) for nb in color_code]
def merge_dicts_with_function(dict_0, dict_1, function): """ Merge dict_0 and dict_1, apply function to values keyed by the same key. Arguments: dict_0 (dict); dict_1 (dict): function (callable): Returns: dict: merged dict """ merged_dict = {} for k in dict_...
def digest(cud): """Reads tuples. Returns a dictionary.""" corpus = {} for i in cud: corpus.setdefault(i[:-1], []).append(i[-1]) return corpus
def vect3_prod_v(_V1, _V2): """ Returns vector product of 3d vectors V1 and V2 """ return [_V1[1]*_V2[2] - _V1[2]*_V2[1], _V1[2]*_V2[0] - _V1[0]*_V2[2], _V1[0]*_V2[1] - _V1[1]*_V2[0]]
def get_type(o): """ Handy wrapper for logging purposes :param o: any object :return str: Nice type name """ return type(o).__name__
def convert_to_celsius(fahrenheit: float) -> float: """ :param fahrenheit: float :return: float """ return(fahrenheit - 32.0) * 5.0 / 9.0
def toBool(val): """ Coerce a string value to a bool. Meant to be used to parse HTTP parameters, which are always sent as strings. The following string values will be interpreted as True: - ``'true'`` - ``'on'`` - ``'1'`` - ``'yes'`` All other strings will be interpreted as...
def _params_to_ints(qs): """Convert a (string) list of string ids to a list of integers""" return [int(str_id) for str_id in qs.split(',')]
def merge(listA, listB): """Merges two lists together""" if len(listA) < 1: return listB if len(listB) < 1: return listA listA_index = 0 listB_index = 0 merged_list = [] total_length = len(listA) + len(listB) while listA_index + listB_index < total_length: if l...
def is_valid_go_command(cmd): """ Test if it is a valid go command: ``.go 1.23 4.56 7.89 0`` """ try: if cmd != cmd.strip(): return False if not cmd.startswith(".go"): return False if cmd.count(" ") != 4: return False chunks = cmd.split...
def get_unique_office_name(element=None): """Provide an autogenerated unique <office:name> for the document. """ if element is not None: body = element.document_body else: body = None if body: used = body.get_office_names() else: used = [] # unplugged current ...
def pprint_row(formatter, data, returned_metrics): """ Return a pretty printed string with a row of the metric streaming output, consisting of the values of the metrics. """ try: parts = [u'{0}'.format(next(iter(data.items()))[1].timestamp)] except (StopIteration, AttributeError): ...
def _findfirst(s, substrs): """Finds whichever of the given substrings occurs first in the given string and returns that substring, or returns None if no such strings occur. """ i = len(s) result = None for substr in substrs: pos = s.find(substr) if -1 < pos < i: i = ...
def compute_predecessors(nodes): """Build a transitive closure. For a list of nodes, compute all the predecessors of each node. Args: nodes: A list of nodes or blocks. Returns: A dictionary that maps each node to a set of all the nodes that can reach that node. """ # Our CFGs are reflexive: Ev...
def extract_capabilities(text): """Extract a capabilities list from a string, if present. Args: text: String to extract from Returns: Tuple with text with capabilities removed and list of capabilities """ if b"\0" not in text: return text, [] text, capabilities = text.rstrip().spl...
def _filter_contacts(ions, contacts, loose): """ Filter the precalculated contacts to ensure they make sense Specifically: Sort the contacts by distance and then by residue and if possible include at most 1 atom per residue and at most 4 residues so max 4 contacts per ion. I...
def _pressure_from_hybrid(psfc, hya, hyb, p0=100000.): """Calculate pressure at the hybrid levels.""" # This will be in Pa return hya * p0 + hyb * psfc
def getVersionString(plist, key=None): """Gets a version string from the plist. If a key is explicitly specified, the value of that key is returned without modification, or an empty string if the key does not exist. If key is not specified: if there's a valid CFBundleShortVersionString, return...
def _retrieve_task_id(res_id, job_dict): """ internal function to retrieve a matching job id for create_bag_by_irods celery task from a specified celery job dictionary including active jobs, reserved jobs, and scheduled jobs. Active jobs and reserved jobs have the same dictionary format, while schedule ...
def _transient_string_in_exception_message(exc): # type: (Exception) -> bool """Determines whether an exception's message contains a common message for transient errors. The exception's message containing one of these substrings is sufficient to determine that it is transient, but there can be transien...
def binarySearchBool(x, L): """Purpose: to search through a list and return a boolean stating if a speci- fic value is present in that list Parameters: x, the value in question, and L, the list to be searched through Return: isIn, a boolean stating whether the value is in the list or not""" i...
def check_name_length(feature_name): """ check the maximum name length for file geodatabase feature classes, if exceed, 160 characters would be returned """ if len(feature_name) > 160: feature_name = feature_name[:160] return feature_name
def oracle_nvl2(expr1, expr2, expr3): """ NVL2(expr1, expr2, expr3) NVL2 lets you determine the value returned by a query based on whether a specified expression is null or not null. If expr1 is not null, then NVL2 returns expr2. If expr1 is null, then NVL2 returns expr3. """ if expr1: ...
def total_speed(speed_list): """ Compute the sum of all speeds in the speed_list. :param speed_list: A list of objects that have a speed_mb attribute. :returns: Speed as an integer. """ speed_mb = 0 if speed_list: for port in speed_list: if port.get_speed_mb(): ...
def change(seq, start, end, change): """Return the sequence with ``seq[start:end]`` replaced by ``change``""" return seq[:start] + change + seq[end:]
def serialise_double(i, context=None): """Serialise a Double value. i -- integer (1 or 2) (unknown values are treated as 1) """ if i == 2: return "2" return "1"
def add_fullstop(text, stop_chars='.?!', replace_chars=';:,-/'): """ Add a fullstop to the end of a string if it does not exist """ text = text.strip() if replace_chars is not None: if text[-1] in replace_chars: text = text[0:-1] return add_fullstop(text, stop_chars=stop_char...
def destos_to_binfmt(key): """ Returns the binary format based on the unversioned platform name, and defaults to ``elf`` if nothing is found. :param key: platform name :type key: string :return: string representing the binary format """ if key == 'darwin': return 'mac-o' elif key in ('win32', 'cygwin', 'uw...
def parse_metric(metric): """ function to parse the metric into dictionary """ return dict({ "value": metric })
def clean_bool_value_from_dict_object(dict_object, dict_name, dict_key, post_errors, no_key_allowed=False): """ This function takes a target dictionary and returns the boolean value given by the given key. Returns None if key if not found and appends any error messages to the post_errors list :param di...
def find_biggest_value_per_day(day_data): """ Take pressure data per day and find biggest value. If some systolic and other systolic equal, compare by diastolic """ values = [(data[2], data[3]) for data in day_data] systolic, diastolic = max(values) return systolic, diastolic
def sqrt_iterative(x, init, k): """using privpy's method for final result. for initial value form bit, we set k=4. for initial value from comp, we set k=7. """ for _ in range(k): init = 0.5*init*(3 - x*init*init) return init * x
def sortArrayByParity(A): """ :type A: List[int] :rtype: List[int] """ return [i for i in A if i % 2 == 0] + [i for i in A if i % 2 != 0]
def _pop_message(message): """Pops the top-most space-separated component from the message.""" if " " in message: component, message = message.split(" ", 1) return component, message.lstrip(" ") return message, ""
def _get_subdict(master_dict, subkeys): """Helper method to get a set of keys from a larger dictionary""" return {k: master_dict[k] for k in subkeys if k in master_dict and master_dict[k] is not None}
def compare_two_hit_id_lists(ids1, ids2): """Take two lists of sequence IDs, and remove ids so that each list contains only unique ids. """ # Copy the input lists. ids1a = ids1 ids2a = ids2 # Make the lists the same length. if len(ids1a) > len(ids2a): ids2a = ids2a + ["Filler"]*...
def refresh_voter_primary_email_cached_information_by_voter_we_vote_id(voter_we_vote_id): """ Make sure this voter record has accurate cached email information. :param voter_we_vote_id: :return: """ results = { 'success': False, 'status': "TO_BE_IMPLEMENTED", } return ...
def get_contact_timings(contact_states): """ :param contact_states: :return: contact start timings, contact end timings """ start_frames = [] end_frames = [] if contact_states[0] is True: start_frames.append(0) for i in range(1, len(contact_states)): if contact_states[...
def normalize_angle_deg(angle: float) -> float: """ Given an angle in degrees, normalises in [-179, 180] """ # ATTRIBUTION: https://github.com/Gor-Ren/gym-jsbsim new_angle = angle % 360 if new_angle > 180: new_angle -= 360 return new_angle
def to_kwh(joules): """ Converts from watts used in a timeframe (in hours) to kwh """ watt_hours = joules return watt_hours / 1000
def u_global(name, prefix='u_', suffix=''): """Returns the uncertainty corresponding to a column. For example, the column ('roi_atoms', 'Fz', '', '') has uncertainties in the column ('roi_atoms', 'u_Fz', '', '') """ if type(name) == tuple: i = len(name)-1 while not name[i]: ...
def cuda_infinity_norm(a, b): """ Use @reduce decorator for converting a simple binary operation into a reduction kernel. :param a: :param b: :return: """ return max(abs(a), abs(b))
def find_kmers(seq, k): """ kmers value""" n = len(seq) - k + 1 return [] if n < 1 else [seq[i:i + k] for i in range(n)]
def parse_formatted_fftlen(fftlen: str) -> int: """Parse a formatted FFT length.""" if fftlen.endswith(('m', 'M')): mega = int(fftlen[:-1]) return mega * 2**20 elif fftlen.endswith(('k', 'K')): kilo = int(fftlen[:-1]) return kilo * 2**10 else: return int(fftlen)
def find_par(s): """returns first parenthese substring""" sub = "" par = 0 start = False for c in s: if c != '(' and not start: continue elif c == '(': par += 1 start = True elif c == ')': par -= 1 if start: ...
def cir_RsQ(w, Rs, Q, n): """ Simulation Function: -Rs-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] """ return Rs + 1/(Q*(w*1j)**n)
def deep_sort(obj): """ Recursively sort list or dict nested lists """ if isinstance(obj, dict): _sorted = {} for key in sorted(obj): _sorted[key] = deep_sort(obj[key]) elif isinstance(obj, list): new_list = [] for val in obj: new_list.append...
def _escape_shell_chars(arg): """ An attempt to sanitize shell arguments without disabling shell expansion. >>> _escape_shell_chars('This (; file has funky chars') 'This \\(\\; file has funky chars' """ arg = arg.replace("(", "\\(") arg = arg.replace(";", "\\;") arg = arg.replace(")...
def to_seconds(s): """Takes str s in HH:MM:SS, MM:SS, or SS format and returns total seconds (integer).""" ssmmhh = [int(n) for n in reversed(s.split(":"))] # only [SS]; we allow user to give us any positive number of seconds if len(ssmmhh) == 1 and ssmmhh[0] >= 0: return ssmmhh[0] # [SS, MM...
def calculate_intervals_from_range(list_range): """ Merge a list of continuous indexes into list of intervals. Parameters: list_range -- A list with compartment indexes to be merged into intervals. Output: A list of lists with intervals. """ list_range = list(list_range) intervals...
def fully_qualified_stack_name(org: str, project: str, stack: str) -> str: """ Returns a stack name formatted with the greatest possible specificity: org/project/stack or user/project/stack Using this format avoids ambiguity in stack identity guards creating or selecting the wrong stack. Note that...
def extract_http_tags(event): """ Extracts HTTP facet tags from the triggering event """ http_tags = {} request_context = event.get("requestContext") path = event.get("path") method = event.get("httpMethod") if request_context and request_context.get("stage"): if request_context....
def calculate_edit_distance(org_code, cand_code): """ The higher the score, the lower the similarity. Pay attention to \n symbol in the line """ org_parts = [part.strip() for part in org_code.strip().split()] cand_parts = [part.strip() for part in cand_code.strip().split()] def levenshteinDistance(s...
def ps_good_mock(url, request): """ Mock for PTCRB lookup, best case. """ thebody = "<table></table><table><td>CER-59665-001 - Rev2-x05-05</td><td>10.3.3.2205</td><td>snek</td><td>OS Version: 10.3.0.1052 Radio Version: 10.3.0.1053 SW Release Version: 10.3.0.675</td></table>" return {'status_code': 2...
def one_of_in(lst, val): """ Returns True if one of the items in the given list exists in the given value, False otherwise. """ for l in lst: if l in val: return True return False
def get_checklist(full_name): """ Generate a list of names that may contain the 'full_name'. Notes: Eg. if full_name looks like "a.b.c", then the list ["a.b.c", "a.*", "a.b.*", "a.b.c.*"] is generated. So either the full name itself may be found, or when full_name is included ...
def dot(coords1, coords2): """ Find the dot product of two 3-dimensional points Parameters coords1: coordinates of form [x,y,z] coords2: coordinates of form [x,y,z] Returns value: Dot product coords2 and coords1 (float) """ value = 0.0 for i ...
def reorder_proper_torsions(i0, i1, i2, i3): """Return the atom indices of a proper torsion after "flipping" the order so that the first atom is the smallest index. Parameters ---------- i0, i1, i2, i3 : int, Atom indices of torsion Returns ------- j0, j1, j2, j3 : int, ...
def make_minimal_cs_thread(overrides=None): """ Create a dictionary containing all needed thread fields as returned by the comments service with dummy data and optional overrides """ ret = { "type": "thread", "id": "dummy", "course_id": "dummy/dummy/dummy", "commentab...
def combine_options(options=None): """ Returns the ``copy_options`` or ``format_options`` attribute with spaces in between and as a string. If options is ``None`` then return an empty string. Parameters ---------- options : list, optional list of strings which is to be converted into a sing...
def parse_fasta(fastalines, zip_entries = True): """ Interprets the input as a string encoding an entire FASTA file. If zip_entries then the return is a list of (id, seq) tuples. Otherwise return is two lists """ ids = [] seqs = [] curr_id = '' curr_seq = [] lines = fastalines.splitlines() for line in l...
def create_group(key, name): """create a group of keys: node of our tree""" res = {} res['name'] = name res['key'] = key res['keys'] = [] res['groups'] = [] res['children'] = [] return res
def prep_filesize(file_size): """ Convert file size to float. :param file_size: Number to parse. :type file_size: float """ if file_size is None: file_size = 0.0 fsize = float(file_size) return fsize
def hamming_distance(v1, v2): """ Get Hamming distance between integers v1 and v2. :param v1: :param v2: :return: """ return bin(v1 ^ v2).count("1")
def _get_extra_configmaps_and_metrics(resource_name, resource_qsets): """ configmap used for logbeat """ extra_configmaps, metrics = [], [] for res in resource_qsets: cms, mts = res.get_extra_configmaps_and_metrics(resource_name) extra_configmaps.extend(cms) metrics.extend(mt...
def reduce_vector(V, p): """ Reduces a vector over finite field. """ for i, element in enumerate(V): V[i] = element % p return V
def folder_name(unit_name): """ Extract folder name from full unit name Example: Unit 01 - Example unit returns: Unit 01 """ return unit_name.strip()
def fs_get_file_id(filelist): """Returns a dict associating filename to figshare file id Parameters ---------- filelist : list of dict HTTP request response from fs_get_file_list Returns ------- response : dict keys are filname and values are file_id """ return {f["...
def sort_by(attribute, iterable, new=False, reverse=False): """Sort an iterable by an attribute of the instance (or dictionary) within the iterable. :param attribute: The name of the attribute by which the iterable should be sorted. :type attribute: str :param iterable: An iterable (such as a list or ...
def read_key_safe(obj, keys, default): """ Recursively check if key is in obj and return the value. Otherwise, return default. """ for key in keys: if key in obj: obj = obj[key] else: return default return obj
def PrivacyChoiceStrength(privacy): """Returns privacy strength (stronger privacy means higher returned value).""" if privacy == 'public-contact-data': return 0 if privacy == 'redacted-contact-data': return 1 if privacy == 'private-contact-data': return 2
def do_range(stop): """ Wrap the standard range() method, to enable things like {% for i in range(6) %} ... """ return list(range(stop))
def read_metadata(line, search_text, current_value): """ Function to read simple header items in DynAdjust files :param line: DynAdjust header line :param search_text: header field required. :param current_value: stored value. Updated when search_text is successfully found. :return: either curre...
def get_nested_dict_value(input_dict, key): """Uses '.' or '->'-splittable string as key to access nested dict.""" if key in input_dict: val = input_dict[key] else: key = key.replace("->", ".") # make sure no -> left split_key = key.split('.', 1) if len(split_key) == 2: ...
def compute_patk(matches, k): """ :param matches: list :param k: float :return: float """ num_matches = 0 for x in matches[:k]: if x: num_matches += 1 return float(num_matches)/k
def make_all_seqs(l): """ Makes all possible sequences, including Ns, of length l """ if l > 8: print("Warning - large barcodes detected!") print("It may be faster to use option '--dont_build_reference'!") nts = ['A', "C", "G", "T", "N"] all_seqs = nts for i in range...
def sort_dic(dic, switch, is_reverse): """ Function: sort dictionary according to keys or values. Input: - dic: Dictionary. - switch: str. "keys" or "values" to sort. - is_reverse: whether or not to sort reversely. Output: Dictionary. sorted. """ if(switch == 'keys'): return {k: v for k, v in sort...
def extract_dependencies(nodes, dependencies): """ Transform dependencies from the file into a dependency dictionary :param nodes: :param dependencies: :return: """ dependencies_dict = {} for node in nodes: dependencies_dict[node] = [] for dependency in dependencies: ...
def Phi_mean_periodic_lorentz(gamma, A_mean): """returns the mean values of a process of periodic Lorentz pulses with duration time td = 1""" I_1 = 1 return gamma * A_mean * I_1
def generate_numbers(count, mean, stdDev, ordering="Random"): """Generates a series of number according to the parameters with a uniform distribution. Possible orderings are: 'Random' (default), 'Sorted', 'Reverse Sorted'""" if (ordering != "Random" and ordering != "Sorted" and ordering != "...
def is_whitelist_file(file_name): """White list documents that are exempt from validation.""" return file_name.endswith("_markers_denormalized.tsv") or file_name.endswith("_Allen_markers.tsv")
def delete_comments(input_text): """ Completely delete all the comments in the input_text. Type 1 comments: "<# ... #>". Type 2 comments: "# ... \n", except for cases when # is surrounded with " or '. :param input_text: a string representing a script to work on. :return: an input_text free...