content
stringlengths
42
6.51k
def f_measure(precision, recall): """ Computes the F1-score for given precision and recall values. :param precision: the precision value :type precision: float :param recall: the recall value :type recall: float :return: F1-score (or 0.0 if both precision and recall are 0.0) """ if pre...
def must_separate(nodes, page_tree): """Given a sequence of nodes and a PageTree return a list of pairs of nodes such that one is the ascendant/descendant of the other""" separate = [] for src in nodes: m = page_tree.match[src] if m >= 0: for tgt in range(src+1, m): ...
def get_header(line): """Return author, urgency, and timestamp from first line""" # delete empty str elements from list def _de(olist): nlist = [] for oitem in olist: if not oitem == str(''): nlist.append(oitem) return nlist try: # replace br...
def get_function_parameters(function): """ Return a list of query parameters that are documented using api.decorators.query_arg """ parameters = [] for name, description, return_type, required in getattr(function, 'doc_query', []): parameters.append({ 'name': name, ...
def charValue(char): """ :param char: Characters for which I want to :return: the integer value of the character """ if 'A' <= char <= 'Z': return ord(char) - 65 elif 'a' <= char <= 'z': return ord(char) - 71
def bevel_2d(point): """ Which of the twelve edge plane(s) is point P outside of? """ edge_plane_code = 0 if point[0] + point[1] >= 1.0: edge_plane_code |= 0x001 if point[0] - point[1] >= 1.0: edge_plane_code |= 0x002 if -point[0] + point[1] > 1.0: edge_plane_code |=...
def match(parent, child): """ :param parent: str, user can input a sequence that is going to be matched. :param child: str, user can input a sequence that is going to match with parent. :return: float, the ratio of how similar the child is to the parent. """ c = len(child) numerator = 0 ...
def back_indel_shift(info_index_list, cur_index) -> int: """return acc_shift(back_indel_shift) Args: info_index_list (list/tuple): list or tuples generated from align.cigar tuples cur_index (int): index related to MD tag in BAM file Returns: int: acc_shift index """ # parse...
def fix_label(label): """Splits label over two lines. Args: label (str): Phrase to be split. Returns: label (str): Provided label split over two lines. """ half = int(len(label) / 2) first = label[:half] last = label[half:] last = last.replace(' ', '\n', 1) return...
def get_solute_data_from_db(solute_spc, db): """ Returns solute data found from the RMG solute library and corresponding comment. """ if solute_spc is not None: data = db.get_solute_data_from_library(solute_spc, db.libraries['solute']) if data is not None: solute_data = data[...
def cleanpath(name): """jref$n4e12510j_crr.fits --> n4e12510j_crr.fits""" if "ref$" in name: return name.split("$")[-1].strip() elif name.startswith("crds://"): return name[len("crds://"):] else: return name
def _flatten_dict(xs): """Flatten a nested dictionary. The nested keys are flattened to a tuple. Example:: xs = {'foo': 1, 'bar': {'a': 2, 'b': {}}} flat_xs = flatten_dict(xs) print(flat_xs) # { # ('foo',): 1, # ('bar', 'a'): 2, # } Note that empty dictionaries are ignored an...
def quote(s): """ Ensure that primary key values do not confuse the admin URLs by escaping any '/', '_' and ':' characters. Similar to urllib.quote, except that the quoting is slightly different so that it doesn't get automatically unquoted by the Web browser. """ if type(s) != type(''): ...
def file_length_checker(file_name): """ Checks the length of the file returned to the validator :param file_name: path of the file to be checked :return: """ result = open(file_name, "r") counter = 0 for line in result: counter += 1 return counter <= 1000
def hash(s, const): """Calculate the hash value of a string using base. Example: 'abc' = 97 x base^2 + 98 x base^1 + 99 x base^0 @param s value to compute hash value for @param const int to use to compute hash value @return hash value """ v = 0 p = len(s)-1 for i in reversed(range(p+...
def find_key(dict_obj, key): """ Return a value for a key in a dictionary. Function to loop over a dictionary and search for an specific key It supports nested dictionary Arguments: dict_obj (obj): A list or a dictionary key (str): dictionary key Return: (li...
def depth_first_flatten(task, task_array=None): """Does a depth first flattening on the child tasks of the given task. :param task: start from this task :param task_array: previous flattened task array :return: list of flat tasks """ if task_array is None: task_array = [] if task: ...
def _extract_variants(address, variants_str): """Return the variants (if any) represented by the given variants_str. :returns: The variants or else `None` if there are none. :rtype: tuple of tuples (key, value) strings """ def entries(): for entry in variants_str.split(','): key, _, value = entry.p...
def _limit(value, min_value, max_value): """Limit value by min_value and max_value.""" if value < min_value: return min_value if value > max_value: return max_value return value
def get_ids_from_j(j, n, control_string, is_numerator): """Get the id of the vector items.""" static_str = control_string + str(int(is_numerator)) bits = n - j if bits > 0: bit_format = "{:0" + str(bits) + "b}" ids = [int(static_str + bit_format.format(i), 2) for i in rang...
def xxxxxx(x, y, z): """if z return x, else return y""" if z: # we're returning an integer, but the signature # says we're returning a float. # PyXLL will convert the integer to a float for us. return x return y
def get_dict_value(adict, key, prefix=None, as_array=False, splitter='.'): """Used to get value from hierarhic dicts in python with params with dots as splitter""" if prefix is None: prefix = key.split(splitter) if len(prefix) == 1: if type(adict) == type({}): if not prefix[0] in...
def max_sub_array(nums): """ Returns the max subarray of the given list of numbers. Returns 0 if nums is None or an empty list. Time Complexity: O(n) Space Complexity: O(n) """ if nums == None: return 0 if len(nums) == 0: return 0 max_sum = 0 current_sum ...
def __compute_num_layers(bpp, extra_bits, layer_bits=64): """ Computes the number of 'layers' required to store the original image with bpp bits-per-pixel along with the results of len(extra_bits) filtered versions of the image, each requiring bpp + extra_bits[i] bits. The filters are done in that order...
def check_output_options(input,): """ Checks the inputs of the mcmc_options dictionary and ensures that all keywords have valid values. output_options={ 'write_chain' : False,# Write MCMC chains for all paramters, fluxes, and # luminosities to a FITS table We set this to false ...
def augment_lab_config(lab_config): """augment the configuration by - adding a "connected_to" attribute to each port which has a cable plugged in Args: lab_config (dict): [description] Returns: dict: lab_config """ for cable in lab_config["cables"]: lab_config["devices"][cable["sour...
def get_bitfinex_api_url(url: str, pagination_id: int) -> str: """Get Bitfinex API URL.""" if pagination_id: return url + f"&end={pagination_id}" return url
def validate_password(value): """ Returns 'Valid' if password provided by user is valid, otherwise an appropriate error message is returned """ if not value: message = 'Please enter password.' elif not len(value) >= 8: message = 'Password must be at least 8 characters.' else:...
def get_skiprows(workbook, sheets): """ Skip the the first row containing ACENAPHTHENE or #ACENAPHTHENE Headers can't be automatically derived """ result = {} for sheetnum in sheets: if sheetnum == 37: col = 1 else: col = 0 sheet = workbook.worksheets[sheetnum] for i,row in enumerate(sheet.rows): ...
def apply_penalty(tensor_or_tensors, penalty, **kwargs): """ Computes the total cost for applying a specified penalty to a tensor or group of tensors. Parameters ---------- tensor_or_tensors : Theano tensor or list of tensors penalty : callable **kwargs keyword arguments passed ...
def get_payload_bits(payload_bytes): """Return a list of bits from a list of bytes Keyword arguments: payload_bytes -- a list of bytes""" payload_bits = list() #convert each byte to a sequence of bits for byte in payload_bytes: temp = list() for i in range(8): temp.append(byte >> i & 1) #temp has the b...
def split_crc_idx(idx): """ split crc index into tem/ccc/rc tuple """ return (idx/16, (idx/4)%4, idx%4)
def time_formatter(seconds: float) -> str: """ humanize time """ minutes, seconds = divmod(int(seconds),60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ((str(days) + "d, ") if days else "") + \ ((str(hours) + "h, ") if hours else "") + \ ((str(minu...
def svd_columns(feature_count, list_of_signals=["current_sub", "current_main"]): """Creates a dictionary of all the SVD column names for each of the signals it is to be applied to. Parameters =========== feature_count : int The number of singular-value-decomposition values to be included ...
def probability(yes, no=1): """Computes the probability corresponding to given odds. Example: yes=2, no=1 means 2:1 odds in favor, or 2/3 probability. yes, no: int or float odds in favor """ return float(yes) / (yes + no)
def get_scale_factor(scale, max_size, img_h, img_w): """ :param scale: min size during test :param max_size: max size during test :param img_h: orig height of img :param img_w: orig width :return: scale factor for resizing """ short = min(img_w, img_h) large = max(img_w, img_h) i...
def delete_allocation_method(dataset): """Delete key ``allocation method`` if present""" if "allocation method" in dataset: del dataset["allocation method"] return [dataset]
def get_accepted_parameters(response_list): """ Returns a dictionary specifyingS the highest supported encryption and hashing standard that both users support. """ parameters_dict = {'hashing' : 0, 'encryption' : 0} if response_list == None: return parameters_dict else: h...
def startswith_whitespace(text): """Check if text starts with a whitespace If text is not a string return False """ if not isinstance(text, str): return False return text[:1].isspace()
def CeilNeg(n): """ Rounds up the provided number :param n: The number to round, Must be negative :return: The result of math.ceil(n) """ if n - int(n) < 0: return int(n - 1) return int(n)
def ip_str_from4bytes(s: bytes) -> str: # b'\xc0\xa8\xfa\xe5' => 192.168.250.229 """ Convert bytestring to string representation of IPv4 address Args: s: source bytestring Returns: IPv4 address in traditional notation """ return str(s[0]) + "." + str(s[1]) + "." + str(s[2]) + "." ...
def processText(text): """ Function for clean text :param text: Text that you need to clean in form of list. :return: return Clean Text """ print(type(text)) for line in text: print(line) return text
def list_max(lst): """ Finds an item in a list that has a maximal value. Returns the index of the item and the value. It ignores items that have value None. If the list is empty or contains only None items, it returns None, None. :param lst: List to search :return: Pair of index (starting from 0) an...
def url_join(domain, *parts): """Construct url from domain and parts. """ if " " in [domain, ] + list(parts): raise Exception("empty string is not allowed in url!") l = list() if domain.endswith("/"): domain = domain[:-1] l.append(domain) for part in parts: for i i...
def popravi_datum(niz): """ Format yyyy-mm-dd spremeni v dd. mm. yyyy. """ return "{2}. {1}. {0}".format(*niz.split("-"))
def norm(value_string): """ Normalize the string value in an RTE pair's ``value`` or ``entailment`` attribute as an integer (1, 0). :param value_string: the label used to classify a text/hypothesis pair :type value_string: str :rtype: int """ valdict = {"TRUE": 1, ...
def quintic_easein(pos): """ Easing function for animations: Quintic Ease In """ return pos * pos * pos * pos * pos
def create_combination(list_of_sentences): """Generates all possible pair combinations for the input list of sentences. For example: input = ["paraphrase1", "paraphrase2", "paraphrase3"] output = [("paraphrase1", "paraphrase2"), ("paraphrase1", "paraphrase3"), ("paraphrase2", "paraphr...
def __weighted_avg(samples, weight_table, n): """ Averages by weight :param samples: the samples to average :param weight_table: the weight table, if None it's a normal average :param n: the number of samples :return: the average """ return sum(x * (weight_table[i] if weight_table is not...
def match_metadata(table_load_jobs, commit_jobs): """ Attempts to match table load job with commit job via metadata value :param table_load_jobs: list(Job); list of table load Jobs :param commit_jobs: list(Job); list of commit jobs :return dict; { 'matches': [(load_job, commit_job)] ...
def unique(seq): """Remove duplicates from a list in Python while preserving order. :param seq: a python list object. :return: a list without duplicates while preserving order. """ seen = set() seen_add = seen.add """ The fastest way to sovle this problem is here Python is a dynam...
def incident_priority_to_dbot_score(score: float) -> int: """Converts the CyberArk score to DBot score representation, while the CyberArk score is a value between 0.0-100.0 and the DBot score is 1,2 or 3. Can be one of: 0.0 - 35.0 -> 1 35.1 - 75.0 -> 2 75.1 - 100.0 -> 3 """ ...
def mint(string): """ Convert a numeric field into an int or None """ if string == "-": return None if string == "": return None return int(string)
def substance_name_match(name, substance): """check if name matches any value in keys we care about""" lower_name = name.lower() return any( [ lower_name == substance[key].lower() for key in ["name", "pretty_name"] if key in substance ] + [lower_na...
def true_solar_time(hour_of_day: float, local_time_constant: float, time_ekvation: float) -> float: """True solar time in hours - DK: Sand soltid""" true_solar_time = hour_of_day + (local_time_constant - time_ekvation) / 60 return true_solar_time
def starts_with_vowel(word): """Check for pronoun compability -- 'a' vs. 'an'""" return True if word[0] in 'aeiou' else False
def modify(boxes, modifier_fns): """ Modifies boxes according to the modifier functions. Args: boxes (dict or list): Dictionary containing box objects per image ``{"image_id": [box, box, ...], ...}`` or list of bounding boxes modifier_fns (list): List of modifier functions that get applied ...
def derivative(v1, v0, t1, t0): """Computes the difference quotient. Returns an approximation of the derivative dv/dt with special handling of delta(t) = 0. """ if t1 > t0: return (v1 - v0) / (t1 - t0) else: return 0
def flatten(value): """ flatten a list """ return [item for sublist in value for item in sublist]
def cant_infer(data): """ Can't infer what data is """ hophop = not data troptrop = True if data else False toptop = data or True return hophop, troptrop, toptop
def _parse_face(face_row): """Parses a line in a PLY file which encodes a face of the mesh.""" face = [int(index) for index in face_row.strip().split()] # Assert that number of vertices in a face is 3, i.e. it is a triangle if len(face) != 4 or face[0] != 3: raise ValueError( 'Only supports face repre...
def get_pipeline_definition(pipeline_name, working_dir): """Return inputs as a mock pipeline loader stub.""" return {'pipeline_name': pipeline_name, 'working_dir': working_dir}
def calc_integration_time(num_groups, frame_time, frames_per_group, num_skips): """Calculates the integration time. Parameters ---------- num_groups : int Groups per integration.] frame_time : float Frame time (in seconds) frames_per_group : int Frames per group -- alway...
def remove_tag(value, arg): """Removes a tag from the selected tags string If more than one tag (contains /) then check if first or follow-on before removing """ if "/" in value: if ("/" + arg) in value: return value.replace(("/" + arg), '') else: ret...
def prepare_check(data): """Prepare check for catalog endpoint Parameters: data (Object or ObjectID): Check ID or check definition Returns: Tuple[str, dict]: where first is ID and second is check definition """ if not data: return None, {} if isinstance(data, str): ...
def multiply_values(dictionary: dict, num: int) -> dict: """Multiplies each value in `dictionary` by `num` Args: dictionary (dict): subject dictionary num (int): multiplier Returns: dict: mapping of keys to values multiplied by multiplier """ return ( {key: value * ...
def utcstr(ts): """ Format UTC timestamp in ISO 8601 format. :param ts: The timestamp to format. :type ts: instance of :py:class:`datetime.datetime` :returns: Timestamp formatted in ISO 8601 format. :rtype: unicode """ if ts: return ts.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" else:...
def selection_sort(A, show_progress=False): """ The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The subarray which i...
def prep_thename(softwareversion, appendbars=False, temp=False): """ Generate name for output file. :param softwareversion: Software release version. :type softwareversion: str :param appendbars: Whether to add app bars to file. Default is false. :type appendbars: bool :param temp: If fil...
def gcd(a, b): """ This is gcd algorithm is the same as the extEuclids. """ if b == 0: return 1, 0, a else: x,y,d = gcd(b, a % b) return y, (x-y*(a//b)), d
def _strings_exists(*strings: str) -> bool: """Check that all of the strings exist and none of them are just the str 'None'.""" for s in strings: if s in ('', 'None'): return False return True
def rook_attack_id(x, y, board, king_x, king_y): """ Function for determining fields that can be blockaded to stop the check of the king for a rook """ indices = [] if king_x == x and king_y < y: dx = 0 dy = -1 elif king_x == x and king_y > y: dx = 0 dy = 1 el...
def to_pixel_format(contour): """OpenCV contours have a weird format. We are converting them to (row, col)""" return [(pixel[0][1], pixel[0][0]) for pixel in contour]
def divide(string, length): """ Taken (with permission) from https://github.com/TheElementalOfCreation/creatorUtils Divides a string into multiple substrings of equal length :param string: string to be divided. :param length: length of each division. :returns: list containing the divided string...
def ids_to_title_artist(dali_dataset): """Transform the unique DALI id to """ output = [[value.info['id'], value.info['artist'], value.info['title']] for key, value in dali_dataset.items()] output.insert(0, ['id', 'artist', 'title']) return output
def sort_selective (array): """ Function how sort the given array b) no only the length of the array c) 21 d) 5 e) 13 f) yes g) 50 - p = 41 c = 125 100 - p = 89 c = 281 500 - p = 457 c = 1422 @type array: list @param array: The list how need to be sorted...
def unique (inlist): """ Returns all unique items in the passed list. If the a list-of-lists is passed, unique LISTS are found (i.e., items in the first dimension are compared). Usage: unique (inlist) Returns: the unique elements (or rows) in inlist """ uniques = [] for item in inlist: if item n...
def smart_truncate(string, max_length=0, word_boundaries=False, separator=' '): """ Truncate a string """ string = string.strip(separator) if not max_length: return string if len(string) < max_length: return string if not word_boundaries: return string[:max_length].strip(...
def _get_term_value(term): """ Auxiliary function: gets str or value from list of value or {key: value} """ if isinstance(term, dict): [(k, v)] = term.items() return v else: return term
def format_dict_counter(dict_counter): """ Format dictionary and rank by sum """ result = [] for k, v in sorted(dict_counter.items(), key=lambda item: item[1], reverse=True): result.append({"budget_type": k, "amount": v}) return result
def _normalized_import_cycle(cycle_as_list, sort_candidates): """Given an import cycle specified as a list, return a normalized form. You represent a cycle as a list like so: [A, B, C, A]. This is equivalent to [B, C, A, B]: they're both the same cycle. But they don't look the same to python `==`. S...
def get_maxlevel(divs, maxlevel): """ Returns the maximum div level. """ for info in divs: if info['level'] > maxlevel: maxlevel = info['level'] if info.get('subdivs', None): maxlevel = get_maxlevel(info['subdivs'], maxlevel) return m...
def are_same(string_window, pat_window): """ This check if two arrays with same length 256 have same count of chars :param string_window: array with counts of char from input string with len of pat string :param pat_window: array with counts of char from pattern string :return:bool True if counts ar...
def bboxes_overlap(bbox_1, bbox_2): """Determines if two bounding boxes overlap or coincide Parameters ---------- bbox_1 : 4-tuple 1st bounding box convention: (minX, minY, maxX, maxY) bbox_2 : 4-tuple 2nd bounding box convention: (minX, minY, maxX, maxY) Retur...
def chk_pfx( msg, p ): """check if msg content contains the given prefix""" return msg[:len(p)] == p
def format_perc(x, dec_places=1): """ format_perc x: a number to format as a percentage dec_places: an integer for the number of digits past the decimal """ format_str = '{{:,.{}f}}%'.format(dec_places) return format_str.format(float(100*x))
def parse_repeat(unparsed_rep): """Parse a repeat returning it as a single item or a list as appropriate.""" if ',' in unparsed_rep: repeat = unparsed_rep.split(',') elif unparsed_rep.isnumeric(): repeat = int(unparsed_rep) else: repeat = unparsed_rep return repeat
def _get_valid_number(section, option, provided): """Validates an int type configuration option. Returns None by default if the option is unset. """ if provided is None: return None try: return int(provided) except ValueError: error = "Value provided for '{0}: {1}' is...
def getBestCols(Matrix, numCols): #expects matrix of floats, except header #no row names """ given a matrix of estimated proportions for each sample, returns the indices of the columns with the highest average values """ outMat = [] TotalValues = [0.0] * len(Matrix[1]) for line in Matrix[1:]:...
def sql_comment(comment: str) -> str: """ Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``. """ """Using -- as a comment marker is ANSI SQL.""" if not comment: return "" return "\n".join(f"-- {x}" for x in comment.splitlines())
def bin_to_gray(bin_list): """ Convert from binary coding to gray coding. We assume big endian encoding. Examples ======== >>> bin_to_gray('111') '100' See Also ======== gray_to_bin """ b = [bin_list[0]] for i in range(len(bin_list) - 1): b += str(int(bin...
def get_value(pairs, key): """Returns a the value for the given key in the given pairs. Args: pairs: A list of {"key": key, "value": value} dicts. key: A key whose value to get. If the key appears more than once, only the first value is returned. Returns: The value for the given key. """ f...
def npv_conf(conf): """compute negative precision""" TN, FP, FN, TP = conf if (TN + FN) == 0: return 0 return TN / float(TN + FN)
def get_heading_indices(row: list) -> dict: """generates a dictionary mapping desired headings to row indices to allow for changing order of columns in source data Args: row (list): row of data from CSV file Returns: dict: dictionary of heading matched with row index """ headings =...
def parse_cmd_out(cmd_out): """Get true of false.""" lines = cmd_out.split("\n") if "True" in lines: return True else: return False
def two_sum(a, b): """ Add ``a`` and ``b`` exactly, returning the result as two float64s. The first is the approximate sum (with some floating point error) and the second is the error of the float64 sum. Using the procedure of Shewchuk, 1997, Discrete & Computational Geometry 18(3):305-363 ...
def number_to_letter(n): """Returns a capital letter representing ordinal position. E.g., 1=A, 2=B, etc. Appends letters once you reach 26 in a way compatible with Excel/Google Sheets column naming conventions. 27=AA, 28=AB... """ string = "" if n is None: n = 0 while n > 0: n, remainder = divmod(n ...
def my_autopct(x): """Function for autopct of plt.pie. This results in values not being printed in the pie if they are 'too small'""" if x > 4: return f"{x:.2f} %" return ""
def get_historical_date(data_point): """Returns the date of a DATA_POINT""" try: return data_point['begins_at'][0:10] except: return None
def convert_to_phrase(target_name): """ we only eliminate _, not /, so "fish tank/bowl" still remains. """ wds = target_name.split(' ') wds = [wd for _ in wds for wd in _.split('_')] return ' '.join(wds)