content
stringlengths
42
6.51k
def NormalsAverage(NormalParameters): """Returns the "average" of the normal distributions from NormalParameters. NormalParameters: a list of length 2 lists, whose entries are the mean and SD of each normal distribution.""" return [sum([Parameter[0] for Parameter in NormalParameters])/(len(NormalParameters)), \ (sum([Parameter[1]**2 for Parameter in NormalParameters])/(len(NormalParameters)**2))**(1/2)]
def truncateToSplice(exons): """ Truncates the gene to only target splice sites """ splice_sites = [] for ind in range(0, len(exons)): splice_sites.append([exons[ind][0], exons[ind][1]-1, exons[ind][1]+1]) splice_sites.append([exons[ind][0], exons[ind][2]-1, exons[ind][2]+1]) # Remove first and last (i.e. transcription start and termination site) return splice_sites[1:len(splice_sites)-1]
def getminmax_linear_search(arr): """ Linear method Initialize values of min and max as minimum and maximum of the first two elements respectively. Starting from 3rd, compare each element with max and min, and change max and min accordingly """ if len(arr) == 0: return None, None if len(arr) == 1: return arr[0], arr[0] min_num = None max_num = None if arr[0] > arr[1]: max_num = arr[0] min_num = arr[1] else: max_num = arr[1] min_num = arr[0] for idx in range(2, len(arr)): if min_num > arr[idx]: min_num = arr[idx] if max_num < arr[idx]: max_num = arr[idx] return min_num, max_num
def multiply_by_1_m(n): """Returns concatenated product of n with 1-m (until digits > 8)""" conc_product = "" i = 1 while len(conc_product) < 9: conc_product += str(n*i) i += 1 return int(conc_product)
def classify_label_list(MAlist, labelset): """Add set of labels to an axonset or create new axonset.""" found = False for i, MA in enumerate(MAlist): for l in labelset: if l in MA: MAlist[i] = MA | labelset found = True break if not found: MAlist.append(labelset) return MAlist
def subtract(value, entries): """Subtract the entry off the value and return another set of remainders""" return {(value - entry) for entry in entries}
def get_gcp_instance_responses(project_id, zones, compute): """ Return list of GCP instance response objects for a given project and list of zones :param project_id: The project ID :param zones: The list of zones to query for instances :param compute: The compute resource object :return: A list of response objects of the form {id: str, items: []} where each item in `items` is a GCP instance """ if not zones: # If the Compute Engine API is not enabled for a project, there are no zones and therefore no instances. return [] response_objects = [] for zone in zones: req = compute.instances().list(project=project_id, zone=zone['name']) res = req.execute() response_objects.append(res) return response_objects
def decode_scoreboard_item(item, with_weight=False, include_key=False): """ :param item: tuple of ZSet (key, score) :param with_weight: keep decimal weighting of score, or return as int :param include_key: whether to include to raw key :return: dict of scoreboard item """ key = item[0].decode('utf-8') data = key.split(">") score = item[1] if not with_weight: score = int(score) output = { 'name': data[0], 'affiliation': data[1], 'tid': data[2], 'score': score } if include_key: output['key'] = key return output
def lr_schedule(epoch, lr=1e-2): """Learning Rate Schedule Learning rate is scheduled to be reduced after 30, 60, 90, 120 epochs. Called automatically every epoch as part of callbacks during training. # Arguments epoch (int): The number of epochs # Returns lr (float32): learning rate """ if epoch > 50: if epoch % 10 == 9: lr *= 0.5e-3 elif 6 <= epoch % 10 < 9: lr *= 1e-3 elif 3 <= epoch % 10 < 6: lr *= 1e-2 elif epoch % 10 < 3: lr *= 1e-1 print('Learning rate: ', lr) return lr
def get_orderedTC_ordering(T: int): """TC swap shuffles temporal ordering, so use this sorting indices to fix it """ if T % 3 == 0: ordering = [(x*(T//3) + x//3) % T for x in range(T)] elif T % 3 == 1: ordering = [(x*((2*T+1)//3)) % T for x in range(T)] else: ordering = [(x*((T+1)//3)) % T for x in range(T)] return ordering
def findORF_all_sorted(dna_seq): """ Finds all the longest open reading frames in the DNA sequence. """ tmpseq = dna_seq.upper(); orf_all = [] for i in range(0, len(tmpseq), 3): codon = tmpseq[i:i+3] if codon == 'ATG': orf = tmpseq[i:] for j in range(0, len(orf), 3): codon = orf[j:j+3] if codon == 'TAA' or codon == 'TAG' or codon == 'TGA': orf_all.append(orf[:j]) break return sorted(orf_all, key=len, reverse=True)
def is_item_visible(item): """Returns true if the item is visible.""" for attr in ['is_deleted', 'is_archived', 'in_history', 'checked']: if item[attr] == 1: return False return True
def check_if_modem_enabled(out): """Given an output, checks if the modem is in the correct mode""" for line in out: if '12d1:1446' in line: return 0 if '12d1:1001' in line: return 1 return -1
def is_philips(dicom_input): """ Use this function to detect if a dicom series is a philips dataset :param dicom_input: directory with dicom files for 1 scan of a dicom_header """ # read dicom header header = dicom_input[0] if 'Manufacturer' not in header or 'Modality' not in header: return False # we try generic conversion in these cases # check if Modality is mr if header.Modality.upper() != 'MR': return False # check if manufacturer is Philips if 'PHILIPS' not in header.Manufacturer.upper(): return False return True
def rotate_r (sequence) : """Return a copy of sequence that is rotated right by one element >>> rotate_r ([1, 2, 3]) [3, 1, 2] >>> rotate_r ([1]) [1] >>> rotate_r ([]) [] """ return sequence [-1:] + sequence [:-1]
def lighten(color, ratio=0.5): """Creates a lighter version of a color given by an RGB triplet. This is done by mixing the original color with white using the given ratio. A ratio of 1.0 will yield a completely white color, a ratio of 0.0 will yield the original color. """ red, green, blue, alpha = color return ( red + (1.0 - red) * ratio, green + (1.0 - green) * ratio, blue + (1.0 - blue) * ratio, alpha, )
def interpretStatus(status, default_status="Idle"): """ Transform a integer globus status to either Wait, Idle, Running, Held, Completed or Removed """ if status == 5: return "Completed" elif status == 9: return "Removed" elif status == 1: return "Running" elif status == 12: return "Held" elif status == 0: return "Wait" elif status == 17: return "Idle" else: return default_status
def preprocess(data): """ Function used to preprocess the input and output for the model. The input gets the special [SEP] token and the output gets a space added. """ return { "input": data['premise'] + '</s>' + data['hypothesis'], "output": str(data['label']) + ' ' + data['explanation_1'], }
def euler_problem_15(n=20): """ Starting in the top left corner of a 2 * 2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20 * 20 grid? """ # this is classic "2n choose n". num_routes = 1.0 # trick to compute (2n)! / n! with less risk of numeric overflow for k in range(1, n + 1): num_routes *= (n + k) / k return round(num_routes)
def WinPathToUnix(path): """Convert a windows path to use unix-style path separators (a/b/c).""" return path.replace('\\', '/')
def markdown_header(header: str, level: int = 1) -> str: """Return a Markdown header.""" return ("\n" if level > 1 else "") + "#" * level + f" {header}\n"
def to_arn(region, account_id, name): """ returns the arn of an SSM parameter with specified, region, account_id and name. If the name starts with a '/', it does not show up in the Arn as AWS seems to store it that way. """ return "arn:aws:ssm:%s:%s:parameter/%s" % ( region, account_id, name if name[0] != "/" else name[1:], )
def append_PKCS7_padding(b): """ Function to pad the given data to a multiple of 16-bytes by PKCS7 padding. @param b data to be padded (bytes) @return padded data (bytes) """ numpads = 16 - (len(b) % 16) return b + numpads * bytes(chr(numpads), encoding="ascii")
def groupIntersections(intersections: list, key: int) -> dict: """ Function to group horizontal or vertical intersections Groups horizontal or vertical intersections as a list into a dict by the given key Parameters: intersections (list): List of tuples representing intersection points key (int): Tuple index to group by (0 for rows and 1 for columns) Returns: dict: Lists of intersections as values grouped by key """ groupedIntersections = {} for intersection in intersections: keyValue = intersection[key] if keyValue not in groupedIntersections.keys(): groupedIntersections[keyValue] = [] group = groupedIntersections[keyValue] group.append(intersection) return groupedIntersections
def ensure_trailing_slash(url): """ensure a url has a trailing slash""" return url if url.endswith("/") else url + "/"
def insertion_sort_descending(dList): """ Given a unsorted list of integers other comparable types, it rearrange the integers in natural order in place in an descending order. Example: Input: [8,5,3,1,7,6,0,9,4,2,5] Output: [9,8,7,6,5,5,4,3,2,1,0] """ n = len(dList) for i in range(n-2, -1, -1): j = i atHand = dList[i] while j < n-1 and atHand < dList[j + 1]: dList[j] = dList[j + 1] j += 1 dList[j] = atHand return dList
def method_to_permcode(method): """ return the django permcode for the specified method eg. "POST" => "add" """ method = method.upper() if method == "POST": return "add" if method == "GET": return "view" if method == "PUT" or method == "UPDATE": return "change" if method == "DELETE": return "delete" raise ValueError("Could not derive perm code from method %s" % method)
def isfloat(value): """ This function checks if a string can be converted to a float. Parameters: ----------- value : string Returns: -------- boolean """ try: float(value) return True except ValueError: return False
def shortText(a,b): """ Returns a short portion of the text that shows the first difference @ In, a, string, the first text element @ In, b, string, the second text element @ Out, shortText, string, resulting shortened diff """ a = repr(a) b = repr(b) displayLen = 20 halfDisplay = displayLen//2 if len(a)+len(b) < displayLen: return a+" "+b firstDiff = -1 i = 0 while i < len(a) and i < len(b): if a[i] == b[i]: i += 1 else: firstDiff = i break if firstDiff >= 0: #diff in content start = max(0,firstDiff - halfDisplay) else: #diff in length firstDiff = min(len(a),len(b)) start = max(0,firstDiff - halfDisplay) if start > 0: prefix = "..." else: prefix = "" return prefix+a[start:firstDiff+halfDisplay]+" "+prefix+b[start:firstDiff+halfDisplay]
def is_entry_a_header(key, value, entry): """Returns whether the given entry in the header is a expected header.""" return (key.lower() in entry.lower() or value.lower() in entry.lower())
def _preprocess_conv2d_input(x, data_format): """Transpose and cast the input before the conv2d. # Arguments x: input tensor. data_format: string, `"channels_last"` or `"channels_first"`. # Returns A tensor. """ if data_format == 'channels_last': # TF uses the last dimension as channel dimension, # instead of the 2nd one. # TH input shape: (samples, input_depth, rows, cols) # TF input shape: (samples, rows, cols, input_depth) x = x.dimshuffle((0, 3, 1, 2)) return x
def b(n, k, base_case): """ :param n: int :param k: int :param base_case: list :return: int """ if k == 0 or k == n: print('base case!') base_case[0] += 1 return 2 else: return b(n-1, k-1, base_case) + b(n-1, k, base_case)
def alternate(seq): """ Splits *seq*, placing alternating values into the returned iterables """ return seq[::2], seq[1::2]
def _make_sent_csv(sentstring, fname, meta, splitter, i, skip_meta=False): """ Take one CONLL-U sentence and add all metadata to each row Return: str (CSV data) and dict (sent level metadata) """ fixed_lines = [] raw_lines = sentstring.splitlines() for line in raw_lines: if not line: continue if line.startswith('#'): if not skip_meta: try: k, v = line.lstrip('# ').split(splitter, 1) except ValueError: k, v = line.lstrip('# ').split(splitter.strip(), 1) meta[k.lower().strip()] = v.strip() else: line = '%s\t%s\t%s' % (fname, i, line) fixed_lines.append(line) return '\n'.join(fixed_lines), meta
def friendly_channel_type(channel_type: str) -> str: """Return a human readable version of the channel type.""" if channel_type == "controlled_load": return "Controlled Load" if channel_type == "feed_in": return "Feed In" return "General"
def compose(*values): """ Compose the specified 8-bit *values* into a single integer. """ result = 0 for i, value in enumerate(values): result |= value << (i * 8) return result
def consecutive_ducks2(n): """ Time complexity: O(1). Space complexity: O(1). """ # Edge case. if n == 2: return False # Check if n is odd, then it can be expressed. if n % 2 == 1: return True # Check if n is power of two, then it cannot be expressed. if n & (n - 1) == 0: return False return True
def daily_mean_t(tmin, tmax): """ Estimate mean daily temperature from the daily minimum and maximum temperatures. :param tmin: Minimum daily temperature [deg C] :param tmax: Maximum daily temperature [deg C] :return: Mean daily temperature [deg C] :rtype: float """ return (tmax + tmin) / 2.0
def thumbnail(value, size): """ Get the thumbnail of 'size' of the corresponding url """ return value.replace('.jpg', '.' + size + '.jpg')
def swaggerFilterByOperationId(pathTypes): """take pathTypes and return a dictionary with operationId as key and PathType object as value Keyword arguments: pathTypes -- list of types that build the model, list of yacg.model.openapi.PathType instances """ ret = {} for pathType in pathTypes: for command in pathType.commands: ret[command.operationId] = pathType return ret
def message(name, pval, alpha=0.01): """Write a message.""" if pval < alpha: return '{0} can be rejected (pval <= {1:.2g})'.format(name, pval) else: return '{0} cannot be rejected (pval = {1:.2g})'.format(name, pval)
def unsanitize(t, mappings): """Unsanitizes a previously sanitized token.""" final = t for original, sanitized in mappings.items(): assert len(original) == 1 final = final.replace(sanitized, original) return final
def hexagonal(nth): """ Providing n'th hexagonal number. :param nth: index for n'th hexagonal :returns: n'th hexagonal number see http://en.wikipedia.org/wiki/Hexagonal_number >>> hexagonal(3) 15 >>> hexagonal(4) 28 """ return nth * (2 * nth - 1)
def add_vec3_vec3(va, vb): """Return the sum of given vec3 values. >>> va = [1,5,-2] >>> vb = [-10,4,6] >>> add_vec3_vec3(va, vb) [-9, 9, 4] """ assert type(va) == list assert type(vb) == list vv = [ None for _ in range(3) ] for row in range(3): vv[row] = va[row] + vb[row] return vv
def format_slack_message(table_name, metric, avg_time, increase, stddev, stddev_old): """ Formats slack message using slack emojis. :param table_name: BigQuery table name that was analysed. :param metric: string with metric name. :param avg_time: calculated average time for recent data of given metric. :param increase: percentage increase. :param stddev: calculated standard deviation based on historical data. :param stddev_old: calculated standard deviation based on historical data. :return: formatted message. """ table_name_formatted = '`{}`'.format(table_name) # Depending on change value bold or highlight and add emoji if increase is None: increase_formatted = "NA" elif increase >= 0: increase_formatted = '`{:+.3f}%` :-1:'.format(increase) else: increase_formatted = '*{:+.3f}%* :+1:'.format(increase) # Bold if value available stddev_formatted = '*{:.2f}*'.format(stddev) stddev_old_formatted = '*{:.2f}*'.format(stddev_old) return '{} - \"{}\", avg_time {:.2f}s, change {}, stddev {}, stddev_old {} \n'.format( table_name_formatted, metric, avg_time, increase_formatted, stddev_formatted, stddev_old_formatted)
def convert_range_to_number_list(range_list): """ Returns list of numbers from descriptive range input list E.g. ['12-14', '^13', '17'] is converted to [12, 14, 17] Returns string with error message if unable to parse input """ # borrowed from [email protected] num_list = [] exclude_num_list = [] try: for val in range_list: val = val.strip(' ') if '^' in val: exclude_num_list.append(int(val[1:])) elif '-' in val: split_list = val.split("-") range_min = int(split_list[0]) range_max = int(split_list[1]) num_list.extend(range(range_min, (range_max + 1))) else: num_list.append(int(val)) except ValueError as exc: return "Parse Error: Invalid number in input param 'num_list': %s" % exc return [num for num in num_list if num not in exclude_num_list]
def fontInfoStyleMapStyleNameValidator(value): """ Version 2+. """ options = ["regular", "italic", "bold", "bold italic"] return value in options
def wallis_product(n_terms): """Implement the Wallis product to compute an approximation of pi. See: https://en.wikipedia.org/wiki/Wallis_product Parameters ---------- n_terms : number for terms in the product. Higher is more precise. Returns ------- pi : approximation of pi """ pi = 2 if n_terms > 0: for n in range(1, n_terms + 1): pi *= (4 * n ** 2) / (4 * n ** 2 - 1) return pi
def isPalindrome(n): """returns if a number is palindromic""" s = str(n) if s == s[::-1]: return True return False
def translate_terms(yamldoc, idspace): """ Reads the `term_browser` field from the given YAML document, validates that it is a supported term browser, and returns a corresponding Apache redirect statement. """ if 'term_browser' in yamldoc and yamldoc['term_browser'].strip().lower() == 'ontobee': replacement = ('http://www.ontobee.org/browser/rdf.php?' 'o=%s&iri=http://purl.obolibrary.org/obo/%s_$1' % (idspace, idspace)) return 'RedirectMatch seeother "^/obo/%s_(\d+)$" "%s"' % (idspace, replacement)
def extractDidParts(did, method="dad"): """ Parses and returns keystr from did raises ValueError if fails parsing """ try: # correct did format pre:method:keystr pre, meth, keystr = did.split(":") except ValueError as ex: raise ValueError("Invalid DID value") if pre != "did": raise ValueError("Invalid DID identifier") if meth != method: raise ValueError("Invalid DID method") return keystr
def get_lines_coordinates(input_data): """extract end coordinates from input text :input data (str): plain text read from txt file :returns end_coordinates (list of list of tuples)""" input_lines = input_data.split("\n") end_coordinates = [] for il in input_lines: if il != "": res = il.strip().split(" -> ") end_coordinates.append( [ (int(res[0].split(",")[0]), int(res[0].split(",")[1])), (int(res[1].split(",")[0]), int(res[1].split(",")[1])), ] ) return end_coordinates
def to_float(val): """Convert string to float, but also handles None and 'null'.""" if val is None: return None if str(val) == "null": return None return float(val)
def function_comments(f): """ Uses single line comments as we can't know if there are string escapes such as /* in the code :param f: :return: """ try: return '\n'.join(["//" + line.strip() for line in f.__doc__.splitlines()]) except AttributeError: return "// No Comment"
def get_label_file_template(doc_name): """ VOTT header file version :param doc_name: Label.json :return: The header for the label.json file """ return { "document": doc_name, "labels": [] }
def validate_isdigit(in_data, key): """Validate if a key value of a dictionary is a pure numeric string This function will check if the the value of a dictionary's key is a string that only includes the digits Args: in_data (dict): The dictionary sent py the patient side client that include all the information uploaded by the users key (string): The key of the dictionry whose value you want to check. Returns: str: "xx is empty" if the key value is an empty string. "xx value id not a numerical string" if the string also includes chars besides digits. True: If the string is not empty and only includes digits """ if in_data[key] == "": return "{} is empty!".format(key) elif in_data[key].isdigit() is False: return "{} value is not a numerical string".format(key) return True
def _flatten_vectors(vectors): """Returns the flattened array of the vectors.""" return sum(map(lambda v: [v.x, v.y, v.z], vectors), [])
def _get_out_class(objs): """ From a list of input objects ``objs`` get merged output object class. This is just taken as the deepest subclass. This doesn't handle complicated inheritance schemes. """ out_class = objs[0].__class__ for obj in objs[1:]: if issubclass(obj.__class__, out_class): out_class = obj.__class__ if any(not issubclass(out_class, obj.__class__) for obj in objs): raise ValueError('unmergeable object classes {}' .format([obj.__class__.__name__ for obj in objs])) return out_class
def get_replication_status(response_json): """ Create a dictionary of the replicated volumes on the cluster This is used to ensure we can track volume ID to volume name from disparate data sources that don't all contain both sets of data """ paired_vols = {} for volume in response_json['result']['volumes']: vol_id = volume['volumeID'] vol_name = volume['name'] paired_vols[vol_id] = vol_name return paired_vols
def getManifestSchemaVersion(manifest): """ returns manifest schema version for manifest""" return manifest["manifest"]["schemaVersion"]
def SFP_update(L, R, t0, t1, u, v): """ Update L and R according to the link (t0,t1,u,v) :param L: :param R: :param t0: :param t1: :param u: :param v: :return: """ su, du, au = L[u] su = -su new_start = min(t1, su) new_arrival = t0 new_distance = du + 1 new_duration = max(new_arrival - new_start, 0) if v in R: current_best_duration = max(R[v][0] - R[v][1], 0) current_best_length = R[v][2] if new_duration < current_best_duration or \ (new_duration == current_best_duration and new_distance < current_best_length): R[v] = (new_arrival, new_start, new_distance) if v in L: sv, dv, av = L[v] sv = -sv if sv >= t0: # Starting time in the future # In this mode we consider best distances for nodes in the future # and we ignore their potential future starting time if new_distance < dv or (new_distance == dv and new_start > sv): L[v] = (-new_start, new_distance, new_arrival) elif new_distance > dv or (new_distance == dv and new_start < sv): return False # else: # return False else: if new_start > sv or (new_start == sv and new_distance < dv): L[v] = (-new_start, new_distance, new_arrival) # elif new_start < sv:# or (new_start == sv and new_distance > dv): # return False else: return False else: L[v] = (-new_start, new_distance, new_arrival) else: L[v] = (-new_start, new_distance, new_arrival) R[v] = (new_arrival, new_start, new_distance) return True
def _is_wav_file(filename): """Is the given filename a wave file?""" return len(filename) > 4 and filename[-4:] == '.wav'
def on_board(position): """Check if position is on board.""" return (0 <= position[0] < 8) and (0 <= position[1] < 8)
def get_unset_keys(dictionary, keys): """ This is a utility that takes a dictionary and a list of keys and returns any keys with no value or missing from the dict. """ return [k for k in keys if k not in dictionary or not dictionary[k]]
def create_dataset_url(base_url, identifier, is_pid): """Creates URL of Dataset. Example: https://data.aussda.at/dataset.xhtml?persistentId=doi:10.11587/CCESLK Parameters ---------- base_url : str Base URL of Dataverse instance identifier : str Identifier of the dataset. Can be dataset id or persistent identifier of the dataset (e. g. doi). is_pid : bool ``True`` to use persistent identifier. ``False``, if not. Returns ------- str URL of the dataset """ assert isinstance(base_url, str) assert isinstance(identifier, str) assert isinstance(is_pid, bool) base_url = base_url.rstrip("/") if is_pid: url = "{0}/dataset.xhtml?persistentId={1}".format(base_url, identifier) else: url = "{0}/dataset.xhtml?id{1}".format(base_url, identifier) assert isinstance(url, str) return url
def one_hot(src_sentences, src_dict, sort_by_len=False): """vector the sequences. """ out_src_sentences = [[src_dict.get(w, 0) for w in sent] for sent in src_sentences] # sort sentences by english lengths def len_argsort(seq): return sorted(range(len(seq)), key=lambda x: len(seq[x])) # sort length if sort_by_len: sorted_index = len_argsort(out_src_sentences) out_src_sentences = [out_src_sentences[i] for i in sorted_index] return out_src_sentences
def type_exists(data, type_name): """Check if type exists in data pack Keyword arguments: data -- data structure where type might be found struct_name -- name of the type to search for """ for established_type in data['types']: if established_type['name'] == type_name: return True return False
def _make_bold_stat_signif(value, sig_level=0.05): """Make bold the lowest or highest value(s).""" val = "{%.1e}" % value val = "\\textbf{%s}" % val if value <= sig_level else val return val
def sum_values(values, period=None): """Returns list of running sums. :param values: list of values to iterate. :param period: (optional) # of values to include in computation. * None - includes all values in computation. :rtype: list of summed values. Examples: >>> values = [34, 30, 29, 34, 38, 25, 35] >>> sum_values(values, 3) #using 3 period window. [34, 64, 93, 93, 101, 97, 98] """ if period: if period < 1: raise ValueError("period must be 1 or greater") period = int(period) results = [] lastval = None for bar, newx in enumerate(values): if lastval == None: lastval = newx elif (not period) or (bar < period): lastval += newx else: oldx = values[bar - period] lastval += (newx - oldx) results.append(lastval) return results
def has_c19_tag (tags): """ Check if the COVID-19 tag is present """ for tag in tags: if tag.vocabulary == "99" and tag.code.upper() == "COVID-19": return True return False
def is_file_like(f): """Check to see if ```f``` has a ```read()``` method.""" return hasattr(f, 'read') and callable(f.read)
def round_to_decimal(value, precision: float = 0.5) -> float: """ Helper function to round a given value to a specific precision, for example *.5 So 5.4 will be rounded to 5.5 """ return round(precision * round(float(value) / precision), 1)
def axLabel(value, unit): """ Return axis label for given strings. :param value: Value for axis label :type value: int :param unit: Unit for axis label :type unit: str :return: Axis label as \"<value> (<unit>)\" :rtype: str """ return str(value) + " (" + str(unit) + ")"
def deobfuscate_value(obfuscation_key, value): """ De-obfuscate a given value parsed from the chainstate. :param obfuscation_key: Key used to obfuscate the given value (extracted from the chainstate). :type obfuscation_key: str :param value: Obfuscated value. :type value: str :return: The de-obfuscated value. :rtype: str. """ l_value = len(value) l_obf = len(obfuscation_key) # Get the extended obfuscation key by concatenating the obfuscation key with itself until it is as large as the # value to be de-obfuscated. if l_obf < l_value: extended_key = (obfuscation_key * ((l_value // l_obf) + 1))[:l_value] else: extended_key = obfuscation_key[:l_value] r = format(int(value, 16) ^ int(extended_key, 16), 'x') # In some cases, the obtained value could be 1 byte smaller than the original, since the leading 0 is dropped off # when the formatting. if len(r) is l_value-1: r = r.zfill(l_value) assert len(value) == len(r) return r
def _get_comparisons_3(idx, paraphrases, other): """Collect basic comparisons: Paraphrases should be closer to their seed than any transformation which significantly changes the meaning of the seed or modality of the seed. """ out = [] for p in paraphrases: for o in other: out.append([(idx, p), (idx, o)]) return out
def remove_multiple_blank_lines(instring): """ Takes a string and removes multiple blank lines """ while '\n\n' in instring: instring = instring.replace('\n\n', '\n') return instring.strip()
def _get_parameter_metadata(driver, band): """ Helper function to derive parameter name and units :param driver: rasterio/GDAL driver name :param band: int of band number :returns: dict of parameter metadata """ parameter = { 'id': None, 'description': None, 'unit_label': None, 'unit_symbol': None, 'observed_property_id': None, 'observed_property_name': None } if driver == 'GRIB': parameter['id'] = band['GRIB_ELEMENT'] parameter['description'] = band['GRIB_COMMENT'] parameter['unit_label'] = band['GRIB_UNIT'] parameter['unit_symbol'] = band['GRIB_UNIT'] parameter['observed_property_id'] = band['GRIB_SHORT_NAME'] parameter['observed_property_name'] = band['GRIB_COMMENT'] return parameter
def string_rotation(x, y): """ :param x: string :param y: string :return: """ if len(x) != len(y): return False new_str = x + x if y in new_str: return True return False
def make_dataframe_value(nrows: int, ncols: int) -> str: """The default value generator for `pandas._testing.makeCustomDataframe`. Parameter names and descriptions are based on those found in `pandas._testing.py`. https://github.com/pandas-dev/pandas/blob/b687cd4d9e520666a956a60849568a98dd00c672/pandas/_testing.py#L1956 Args: nrows (int): Number of rows. ncols (int): Number of columns. Returns: str: "RxCy" based on the given position. """ return f"R{nrows}C{ncols}"
def checkStatus(vL, vA, vB): """ Validacion de las marcas, si el pixel coincide con algun color regresa True """ if (vL >= 40 and vL <= 80) and (vA >= 50 and vA <= 80) and (vB >= -40 and vB <= 10): return True else: return False
def calc_delta(times): """ create time-slices for: 22000, 18000, 14000, 10000, 6000, 2000, 1990 BP """ btime = 22000 # BP if type(times) == list: idx = [(t+btime)*12 for t in times] else: idx = times+btime*12 return idx
def sec_from_hms(start, *times): """ Returns a list of times based on adding each offset tuple in times to the start time (which should be in seconds). Offset tuples can be in any of the forms: (hours), (hours,minutes), or (hours,minutes,seconds). """ ret = [] for t in times: cur = 0 if len(t) > 0: cur += t[0] * 3600 if len(t) > 1: cur += t[1] * 60 if len(t) > 2: cur += t[2] ret.append(start+cur) return ret
def zalpha(z, zmin, zrng, a_min=0): """ return alpha based on z depth """ alpha = a_min + (1-a_min)*(z-zmin)/zrng return alpha
def selectNRandom(nodes, N): """ Selects n random nodes from a list of nodes and returns the list """ import random random.shuffle(nodes) return nodes[:N]
def avgout(vallist): """ entry-wise average of a list of matrices """ r = len(vallist) A = 0 if r > 0: for B in vallist: A += (1.0/r) * B return A
def get_k_for_topk(k, size): """Get k of TopK for onnx exporting. The K of TopK in TensorRT should not be a Tensor, while in ONNX Runtime it could be a Tensor.Due to dynamic shape feature, we have to decide whether to do TopK and what K it should be while exporting to ONNX. If returned K is less than zero, it means we do not have to do TopK operation. Args: k (int or Tensor): The set k value for nms from config file. size (Tensor or torch.Size): The number of elements of \ TopK's input tensor Returns: tuple: (int or Tensor): The final K for TopK. """ ret_k = -1 if k <= 0 or size <= 0: return ret_k if k < size: ret_k = k else: # ret_k is -1 pass return ret_k
def fib(n): """ Returns the nth Fibonacci number. """ if n < 2: return n else: return fib(n-2) + fib(n-1)
def dt2str(dt): """ Convert a datetime object to a string for display, without microseconds :param dt: datetime.datetime object, or None :return: str, or None """ if dt is None: return None dt = dt.replace(microsecond=0) return str(dt)
def get_added_labels(l_new, l_old): """ Get labels that are new to this PR :param l_new: new labels to be added :param l_old: labels that were already in the PR :type l_new: list :type l_old: list :returns: list of labels that were added :rtype: list """ ret = [] for l in l_new: if l in l_old: continue else: ret.append(l) return ret
def percentage_as_number(percent_str): """ Convert a percentage string to a number. Args: percent_str: A percent string, for example '5%' or '1.2%' Usage ===== >>> percentage_as_number('8%') 0.08 >>> percentage_as_number('250%') 2.5 >>> percentage_as_number('-10%') -0.1 """ return float(percent_str.strip()[:-1]) * 0.01
def dict_to_cmdlist(dp): """ Transform a dictionary into a list of command arguments. Args: dp Dictionary mapping parameter name (to prepend with "--") to parameter value (to convert to string) Returns: Associated list of command arguments Notes: For entries mapping to 'bool', the parameter is included/discarded depending on whether the value is True/False For entries mapping to 'list' or 'tuple', the parameter is followed by all the values as strings """ cmd = list() for name, value in dp.items(): if isinstance(value, bool): if value: cmd.append(f"--{name}") else: if any(isinstance(value, typ) for typ in (list, tuple)): cmd.append(f"--{name}") for subval in value: cmd.append(str(subval)) elif value is not None: cmd.append(f"--{name}") cmd.append(str(value)) return cmd
def conv_F2K(value): """Converts degree Fahrenheit to Kelvin. Input parameter: scalar or array """ value_k = (value-32)*(5/9)+273.15 if(hasattr(value_k, 'units')): value_k.attrs.update(units='K') return(value_k)
def _default_validator(value): """A default validator, return False when value is None or an empty string. """ if not value or not str(value).strip(): return False return True
def get_sub_formula(formula): """ "(SO3)2" -> ("(SO3)2", "(SO3)", "2") "(SO3)" -> ("(SO3)", "(SO3)", "") """ import re match = re.search('(\([a-zA-Z\d]+\))(\d*)', formula) if not match: return full_sub_formula = match.group(0) sub_formula = match.group(1) multiplier = match.group(2) return full_sub_formula, sub_formula, multiplier
def cluster_hierarchically(active_sites): """ Cluster the given set of ActiveSite instances using a hierarchical algorithm. # Input: a list of ActiveSite instances Output: a list of clusterings (each clustering is a list of lists of Sequence objects) """ # Fill in your code here! """ #Will use agglomerative clustering #pseudocode: #Input: (1)some active sites, (2) recalculated similarity matrix between those active sites #output: some clusterings of activesites #while TRUE do #a single cluster <-- each original active site #find a pair of clusters (a) and (b) such that their similarity s[(a),(b)] = max(s[(m),(n)]); #if (s[(a),(b)]) < or = to some threshold, then #terminate the while loop; #else #merge (a) and (b) into a new cluster(a+b); #update similarity matrix by deleting both the row and the column corresponding to (a) and (b); #end #end #output current clusters containing similar activesites """ return []
def get_crop_range(maxX, maxY, size=32): """Define region of image to crop """ return maxX-size, maxX+size, maxY-size, maxY+size
def hardlims(n): """ Symmetrical Hard Limit Transfer Function :param int n:Net Input of Neuron :return: Compute Heaviside step function :rtype: int """ if n<0: return -1 else: return 1
def zeroPad(n, l): """Add leading 0.""" return str(n).zfill(l)
def get_accidental(i: int) -> str: """Returns the accidental string from its index, e.g. 1->#.""" s: str = "" if i > 0: s = "x" * (i // 2) + "#" * (i % 2) elif i < 0: s = "b" * abs(i) return s
def what_type(data): """ Description: Identify the data type :param data: raw data (e.g. list, dict, str..) :return: Data type in a string format """ return str(type(data)).split('\'')[1]