content
stringlengths
42
6.51k
def n50(values): """Return the N50 of the list of numbers""" values.sort(reverse=True) target = sum(values) / 2. total = 0 for v in values: total += v if total >= target: return v return 0
def _method_1(a, b): """Thought of this, on the fly, January 15, 2022.""" import string o = 0 for character in string.ascii_lowercase: a_count = a.count(character) b_count = b.count(character) difference = abs(a_count - b_count) if difference > 0: o += differ...
def __is_victory(player_state, victory_condition): """ Returns true if the provided state represents a provided victory state :param player_state: The state under evaluation :param victory_condition: The victory condition to test against :return: True if the state represents the provided victory con...
def strip_enclosing_quotes(string: str) -> str: """Strip leading/trailing whitespace and remove any enclosing quotes""" stripped = string.strip() # Need to check double quotes again in case they're nested inside # single quotes for quote in ['"', "'", '"']: if stripped.startswith(quote) and...
def summ(sin: float, cos: float) -> float: """ Calculate the Z2n power value. Parameters ---------- sin : float A float that represents the sine value. cos : float A float that represents the cosine value. Returns ------- value : float A float that represent...
def unwrap_distributed(state_dict): """ Unwraps model from DistributedDataParallel. DDP wraps model in additional "module.", it needs to be removed for single GPU inference. :param state_dict: model's state dict """ new_state_dict = {} for key, value in state_dict.items(): new_ke...
def skip_zone_record(zone_record): """Whether a zone record should be skipped or not. Records are skipped if they are empty or start with a # (indicating a comment). :param zone_record: Full zone record, including the command (e.g. ADD). :returns: True if the record should be skipped, false otherw...
def get_tag_list(keys, tags): """ Returns a list of dicts with tags to act on keys : set of keys to get the values for tags : the dict of tags to turn into a list """ tag_list = [] for k in keys: tag_list.append({'Key': k, 'Value': tags[k]}) return tag_list
def hex2text(hex): """ Convert hex to text :param hex: hex to convert :return: text string """ return ''.join(chr(int(hex[i:i+2], 16)) for i in range(0, len(hex), 2))
def vector_subtract(v, w): """subtrai elementos correspondentes""" return [v_i - w_i for v_i, w_i in zip(v, w)]
def find_parent_row(parsed_rows, parent_name): """ finds a parent row by a given name """ for row in parsed_rows: task_name = row['name'] if not task_name: continue if task_name == parent_name: return row return None
def label_to_AI(labels): """Transforms a list of {0, 1} labels into {-, AI} labels""" return ['AI' if lab == 1 else '-' for lab in labels]
def is_none(x): """ Helper function since x == None doesn't work well on arrays. Returns True if x is None. """ return isinstance(x, type(None))
def available_through_years(available_year_list, start_year): """Return a list of available through/ending years that are >= the start year. :param available_year_list: List of available years from the input file :type available_year_list: list :param start_year: ...
def ip2string(splited_ip): """ Funcion que devuelve el string apropiado para la lista de la IP fragmentada """ return str(splited_ip[0]) + "." + str(splited_ip[1]) + "." + str(splited_ip[2]) + "." + str(splited_ip[3])
def print_dependencies_check(data_string: str) -> str: """ Prints the results of the dependencies check """ try: from colorama import Fore, Style, init init() start_ok_color = Fore.GREEN start_fault_color = Fore.RED stop_color = Style.RESET_ALL except ImportEr...
def mean(dictionary: dict): """ Author: SW Returns the mean of each value in the dictionary for each key :param dictionary: dict: an input dictionary of iterables :return: dict: dictionary with the mean of all values """ for key, value in dictionary.items(): dictionary[key] = sum(val...
def adjust_val_to_360(val): """ Take in a single numeric (or null) argument. Return argument adjusted to be between 0 and 360 degrees. """ if not val and (val != 0): return None else: try: return float(val) % 360 except ValueError: return val
def get_interaction_dict(clean_pdbs, verbose=False): """Generates interaction dictionary. This is a dictionary of dictionaries. Each chain id is the key of the first dictionary, and as value a dictionary. The dictionary inside has tuples of interactiong resiudes (their number) from chain 1 to 2 as keys and ...
def _update_post_node(node, options, arguments): """ Extract metadata from options and populate a post node. """ node["date"] = arguments[0] if arguments else None node["tags"] = options.get("tags", []) node["author"] = options.get("author", []) node["category"] = options.get("category", [])...
def _lang_range_check(range, lang): """ Implementation of the extended filtering algorithm, as defined in point 3.3.2, of U{RFC 4647<http://www.rfc-editor.org/rfc/rfc4647.txt>}, on matching language ranges and language tags. Needed to handle the C{rdf:PlainLiteral} datatype. @param range: langua...
def ind_l1_ball( w, lamb=1 ): """! Compute the indication function of the \f$\ell_1\f$-ball Parameters ---------- @param w : input vector @param lamb : penalty paramemeter Returns ---------- @retval : whether the input is in $\ell_1$-ball """ # norm_w = np.linalg.norm(w, ord=1) # if norm_w > lamb: ...
def get_pass_room_count_honeycomb(position): """ 1-depth room count : 1 (0-1) 2-depth room count : 6 (2-7) 3-depth romm count : 12 (8-19) 4-depth romm count : 18 (20-37) N-depth room count : 6*(N-1) (2+(6*(N-2), 1+(6*N-1)) """ if position == 1: return 1 count = 2 left_ed...
def sum_dicts(source, dest): """ Adds values from source to corresponding values in dest. This is intended for use as a merge_func parameter to merge_value. """ for k, v in source.items(): dest.setdefault(k, 0) dest[k] += v return dest
def versiontuple(v: str) -> tuple: """ Function to converts a version string into a tuple that can be compared, copied from https://stackoverflow.com/questions/11887762/how-do-i-compare-version-numbers-in-python/21065570 """ return tuple(map(int, (v.split("."))))
def mem_to_label(value, mem_split): """turn mem to label""" for index, split in enumerate(mem_split): if value <= split: return index
def is_listlike(x): """ >>> is_listlike("foo") False >>> is_listlike(5) False >>> is_listlike(b"foo") False >>> is_listlike([b"foo"]) True >>> is_listlike((b"foo",)) True >>> is_listlike({}) True >>> is_listlike(set()) True >>> is_listlike((x for x in rang...
def hass_to_unifi_brightness(value): """Convert hass brightness 0..255 to unifi 1..6 scale.""" return max(1, round((value / 255) * 6))
def denormalize(x): """denormalize image CelebA images are mapped into [-1, 1] interval before training This function applies denormalization Arguments: x -- image """ x = x * .5 + .5 return x
def rotations(integer): """gibt eine Liste der Rotationen einer Zahl (197 -> 971 and 719) aus """ zahl = str(integer) rot = [] for i in range(len(zahl)-1): # -1 weg, wenn integer mit ausgegeben werden soll zahl = zahl[-1] + zahl[0:-1] rot.append(int(zahl)) return rot
def by_hex(fg, bg = "#000000", attribute = 0): """ Return string with ANSI escape code for set text colors fg: html hex code for text color bg: html hex code for background color attribute: use Attribute class variables """ # Delete # fg = fg.replace("#", "") bg = bg.replace("#", "...
def is_magic_variable(var_name): """ Determines if a variable's name indicates that it is a 'magic variable'. That is, it starts and ends with two underscores. e.g. '__foo__'. These variables should not be injected. Args: var_name the name of the variable. Returns: True if var_name starts and end...
def edge_count(adjList): """Compute number of edges in a graph from its adjacency list""" edges = {} for id, neigh in enumerate(adjList): for n in neigh: edges[max(n, id), min(n, id)] = id return len(edges)
def get_ruler_auto_size(screenwidth, worldwidth): """get most appropriate unit for zoom level""" unit = 1 order = 0 if worldwidth == 0.0: return unit while True: # find pixels per unit pixelsize = screenwidth / (worldwidth / float(unit)) if pixelsize < 50 and order...
def is_same_url(a, b): """Check if different forms of same URL match""" return a and b and a.strip().strip('/') == b.strip().strip('/')
def clamp(x: float, minimum=0.0, maximum=1.0): """Clamp a number. This is a synonym of clipping. Parameters ---------- x minimum maximum """ return max(min(x, maximum), minimum)
def delta_masso_from_soga(s_orig, s_new, m_orig): """Infer a change in mass from salinity""" delta_m = m_orig * ((s_orig / s_new) - 1) return delta_m
def viewMethod(obj, method): """Fetch view method of the object obj - the object to be processed method - name of the target method, str return target method or AttributeError >>> callable(viewMethod(dict(), 'items')) True """ viewmeth = 'view' + method ometh = getattr(obj, viewmeth, None) if not ometh:...
def string_manipulation(ans_lst): """ change the type of answer from list to string :param ans_lst: list, the process of the answer with list type :return: str, the process of the answer with string type """ word = "" for i in range(len(ans_lst)): word += ans_lst[i] return word
def h2(text): """Heading 2. Args: text (str): text to make heading 2. Returns: str: heading 2 text. """ return '## ' + text + '\r\n'
def verifyInfo(in_dict, sample_dict): """Verify whether the input dictionary is valid. An input dictionary is valid when 1) all the keys in the sample dictionary can be found in the input dictionary; 2) values in the input dictionary should have the same datatype as what in the smaple dictionary Ar...
def truncatechars(value, arg): """ Truncates a string after a certain number of chars. Argument: Number of chars to truncate after. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. if len(value) > length: retu...
def parse_original_im_name(im_name, parse_type='id'): """Get the person id or cam from an image name.""" assert parse_type in ('id', 'cam') if parse_type == 'id': parsed = -1 if im_name.startswith('-1') else int(im_name[:4]) else: parsed = int(im_name[4]) if im_name.startswith('-1') \ else int(im_...
def is_folder(item): """ Check the item's 'type' to determine whether it's a folder. """ return item['type'] == "folder"
def cleanRawText(text): """ vtype text: str rtype text: str / utf8 """ text = text.encode('ascii', 'replace') text = text.replace(b'?', b'') text = text.replace(b'\r\n', b'\n') text = text.replace(b'\n', b' ') text = text.strip() text = text.decode('utf8') return(text)
def needs_marker(string, pattern, marker): """Check if a substring is following a certain marker. Args: string (str) - string to search in pattern (str) - pattern to search for marker (str) - marker to be followed by pattern, can be U, C, M, etc. """ pattern_start_pos = string.find(pa...
def get_relative_error(approximation, real): """Return the relative error of two values""" return abs(approximation - real) / real
def svg_polygon(coordinates, color): """ Create an svg triangle for the stationary heatmap. Parameters ---------- coordinates: list The coordinates defining the polygon color: string RGB color value e.g. #26ffd1 Returns ------- string, the svg string for the polygon...
def value_left(self, right): """ Returns the value of the right type instance to use in an operator method, namely when the method's instance is on the left side of the expression. """ return right.value if isinstance(right, self.__class__) else right
def update_pesos(pesos, muestra, delta): """ Funcion que actualiza pesos """ n_pesos = [] for m, p in zip(muestra, pesos): p = p + m * delta n_pesos.append(p) return n_pesos
def getSquareDistanceOriginal(p1, p2): """ Square distance between two points """ dx = p1['x'] - p2['x'] dy = p1['y'] - p2['y'] return dx * dx + dy * dy
def objectIdentifier(callingObject): """Returns a human-readable string identifier for a provided object. callingObject -- the object to be identified This method figures out the best name to use in identifying an object, taking queues from: - its _name_ attribute, if avaliable - more to b...
def _get_policy_name(policy_arn): """ Translate a policy ARN into a full name. """ return policy_arn.split(':')[-1].split('/')[-1]
def isstringlike(item): """ Checks whether a term is a string or not """ ret = 1 try: float(item) ret = 0 except ValueError: pass return ret
def unbox_usecase(x): """ Expect a list of numbers """ res = 0 for v in x: res += v return res
def godel(x,y): """ >>> godel(3, 81) 3547411905944302159585997044953199142424 >>> godel(51, 29) 154541870963391800995410345984 """ return (2**x)*(3**y)
def VerifyFileOwner(filename): """Verifies that <filename> is owned by the current user.""" # On Windows server OSs, files created by users in the # Administrators group will be owned by Administrators instead of # the user creating the file so this check won't work. Since on # Windows G...
def calculate_total_bill(subtotal): """ (float) -> float subtotal is passed through as an input HST_RATE variable in this function is multiplied by inputted variable Function returns the resulting variable "total", rounded and formatted to 2 decimal points. Variable "total" is then rounded to t...
def startswith_field(field, prefix): """ RETURN True IF field PATH STRING STARTS WITH prefix PATH STRING """ if prefix.startswith("."): return True # f_back = len(field) - len(field.strip(".")) # p_back = len(prefix) - len(prefix.strip(".")) # if f_back > p_back: ...
def intToRoman(num): """ :type num: int :rtype: str """ dict_ = { 1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M' } result = '' remain = num while remain != 0: for i in sorted(dict_, reverse=True): if i <= remain: result += dict_.get(i) remain -= i break return r...
def addGMSHLine( number, startPoint, endPoint ): """ Add a line to GMSH """ string = "Line(" + str(number) + ") = {" + str(startPoint) + ", " + str(endPoint) + "};" return string
def trim(data): """removes spaces from a list""" ret_data = [] for item in data: ret_data += item.replace(' ', '') return ret_data
def convert_bytes(num): """ this function will convert bytes to MB.... GB... etc """ for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: return "%3.2f %s" % (num, x) num /= 1024.0
def normalize_copy(numbers): """ normalize_copy :param numbers: :return: """ numbers = list(numbers) total = sum(numbers) result = [] for value in numbers: percent = 100 * value / total result.append(percent) return result
def tag2ot(ote_tag_sequence): """ transform ote tag sequence to a sequence of opinion target :param ote_tag_sequence: tag sequence for ote task :return: """ n_tags = len(ote_tag_sequence) ot_sequence = [] beg, end = -1, -1 for i in range(n_tags): tag = ote_tag_sequence[i].spl...
def _get_priority_restrictions_regex(max_priority): """Returns something like: ((?!.*tp)|(?=.*tp[0-2]))""" return "((?!.*tp)|(?=.*tp[0-%s]))" % max_priority
def grid_width(cluster_num, i=0): # 3 closest is 4 so return 2; 6 closest is 9 so return 3; 11 closest is 16 so return 4, etc. """ Function to acquire appropriate (square) grid width for plotting. """ while i**2 < cluster_num: i+=1; return i
def getOpString(mean, std_dev): """ Generate the Operand String to be used in workflow nodes to supply mean and std deviation to alff workflow nodes Parameters ---------- mean: string mean value in string format std_dev : string std deviation value in string format ...
def __render_one_rtsec_element(element): """ Takes a message block rich text section element and renders it to a string, which it returns. Private method. """ ret = "" element_type = element.get('type', None) if element_type == "text": # This can contain an optional style block that ...
def speed_of_sound_gas(k, R, T): """ k : ratio of specific heats R : gas constant T : absolute temperature from http://www.engineeringtoolbox.com/speed-sound-d_519.html """ return (k * R * T) ** 0.5
def getSim(w1, w2): """ :param w1: winner cell which should be a list :param w2: :return: simularity score """ w1 = set(w1) w2 = set(w2) return len(w1 & w2) / len(w1 | w2)
def trans_type(code): """Translates transaction code for human readability. :param code: The code to be converted :type code: str :return: Human-readable transaction type :rtype: str """ if code == "B": return "Beginning Balance" if code == "C": return "Check" if cod...
def make_values(repo_pkg, cur_ver, new_ver, branch, check_result): """ Make values for push_create_pr_issue """ values = {} values["repo_pkg"] = repo_pkg values["cur_version"] = cur_ver values["new_version"] = new_ver values["branch"] = branch values["check_result"] = check_result ...
def fibonacci(nth): """ recursive form, according to definition """ if nth>30: print("nth is too big for ") return -1 elif nth> 2: return fibonacci(nth-1) + fibonacci(nth-2) else: if nth== 1: return 1 if nth== 2: ...
def idxs_of_duplicates(lst): """ Returns the indices of duplicate values. """ idxs_of = dict({}) dup_idxs = [] for idx, value in enumerate(lst): idxs_of.setdefault(value, []).append(idx) for idxs in idxs_of.values(): if len(idxs) > 1: dup_idxs.extend(idxs) return ...
def _represent_args(*args, **kwargs): """Represent the aruments in a form suitable as a key (hashable) And which will be recognisable to user in error messages >>> print(_represent_args([1, 2], **{'fred':'here'})) [1, 2], fred='here' """ argument_strings = [repr(a) for a in args] keyword_st...
def generate_file_from_template(template_path, output_path, template_values): """Write to file. Args: template_path (str): Input template path output_path (str): Path of the output file template_values (dict): Values to replace the ones in the input templ...
def sign(x): """Sign of a number. Note only works for single values, not arrays.""" return -1 if x < 0 else 1
def plan_cost(plan): """Convert a plan to a cost, handling nonexistent plans""" if plan is None: return float('inf') else: return len(plan)
def bool_(x): """Implementation of `bool`.""" return x.__bool__()
def format_price(number): """[It takes a float value and converts it to 2 decimal places and appends a '$' in front. Returns the converted value.] Args: number ([float]): [The raw float value with multiple decimal places.] """ #pylint: disable=consider-using-f-string ...
def parseFilterStr(args): """Convert Message-Filter settings in '+<addr> -<addr> ...' format to a dict of the form { '<addr>':True, '<addr>':False, ... } Returns a list: ['<prefix>', filters] """ out = {} if isinstance(args,str): args = [args] prefix = None for arg in args: head = None for plus in a...
def is_bigstore_file(filename): """ Sniff a file to see if it looks like one of ours. :param filename: filename to inspect :return: True if the file starts with `bigstore` """ prefix = 'bigstore\n' try: with open(filename) as fd: return fd.read(len(prefix)) == prefix ...
def extract_vulnerabilities(debian_data, base_release='jessie'): """ Return a sequence of mappings for each existing combination of package and vulnerability from a mapping of Debian vulnerabilities data. """ package_vulnerabilities = [] for package_name, vulnerabilities in debian_data.item...
def version_to_tuple(v): """Quick-and-dirty sort function to handle simple semantic versions like 1.7.12 or 1.8.7.""" if v.endswith('(preview)'): return tuple(map(int, (v[:-9].split('.')))) return tuple(map(int, (v.split('.'))))
def get_patch_position(tile,patch): """ tile: tuple -> (tile x position, tile y position, tile size) patch: tuple -> (patch x position, patch y position, patch size) """ tx,ty,ts = tile px,py,ps = patch return (px-tx,py-ty,ps)
def get_canonical_tensor_name(name: str) -> str: """ Legal tensor names are like: name, ^name, or name:digits. Please refert to: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/graph/tensor_id.cc#L35 """ parts = name.split(":") is_control_input = name.startswith("^") if ...
def vlsp_2018_Acc(y_true, y_pred, score, classes=3): """ Calculate "Acc" of sentiment classification task of VLSP 2018. """ assert classes in [2, 3], "classes must be 2 or 3." if classes == 3: total=0 total_right=0 for i in range(len(y_true)): if y_true[i]==3:con...
def check_for_dict_key(dict, key, **additional_params): """Search for keys and add additiona keys if found.""" if dict.get(key): if additional_params.get('index') is not None: return dict[key][additional_params['index']] else: return dict[key] else: if additio...
def maxProfit(nums): """ https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/ :param nums: :return: """ # n = len(nums) # res = [0 for _ in range(n)] # pre = nums[0] # for i in range(1, n): # pro = nums[i] - pre # res[i] = max(pro, res[i - 1]) # i...
def searchList(listOfTerms, query: str, filter='in'): """Search within a list""" matches = [] for item in listOfTerms: if filter == 'in' and query in item: matches.append(item) elif filter == 'start' and item.startswith(query): matches.append(item) eli...
def _normalize_dicts(dict1, dict2): """Helper function that converts two dicts to lists that are aligned to each other.""" def add_keys_from(dist1, dist2): """If dist1 contains a key that dist2 doesn't, add it to dict2.""" for k in dist1.keys(): if k not in dist2: di...
def path(name): """ Generate a path object """ return {'$OBJECT': 'path', 'paths': [name]}
def cast_pureDP_zCDP(epsilon): """cast a epsilon-DP measurement to a (xi, rho)-zCDP measurement Proposition 1.4: https://arxiv.org/pdf/1605.02065.pdf#subsubsection.1.2.1 """ return 0, epsilon ** 2 / 2 # also valid under Lemma 8.3 # return epsilon, 0
def dotProduct(d1, d2): """ @param dict d1: a feature vector represented by a mapping from a feature (string) to a weight (float). @param dict d2: same as d1 @return float: the dot product between d1 and d2 """ if len(d1) < len(d2): return dotProduct(d2, d1) else: return sum(...
def _merge_secrets(secrets): """ Merge a list of secrets. Each secret should be a dict fitting the following JSON structure: [{ "sourceVault": { "id": "value" }, "vaultCertificates": [{ "certificateUrl": "value", "certificateStore": "cert store name (only on windows)"}] }] The array of s...
def BlendColour(fg, bg, alpha): """ Blends the two colour component `fg` and `bg` into one colour component, adding an optional alpha channel. :param `fg`: the first colour component; :param `bg`: the second colour component; :param `alpha`: an optional transparency value. """ result =...
def convert_ftp_url(url): """Convert FTP to HTTPS URLs.""" return url.replace('ftp://', 'https://', 1)
def _isIp(value): """ Check if the input string represents a valid IP address. A valid IP can be one of the two forms: 1. A string that contains three '.' which separate the string into four segments, each segment is an integer. 2. A string be either "INVALID_IP(XXXl)" or "AUTO/NONE(XXXl)", ...
def configureOutput(path): """configureOutput(path) Set the directory into which results like images and text output files are written.""" return {"Output" : path }