content
stringlengths
42
6.51k
def _world2Pixel(geo_t, x, y, buffer_size = 0): """ Uses a gdal geomatrix (ds.GetGeoTransform()) to calculate the pixel location of a geospatial coordinate. Modified from: http://geospatialpython.com/2011/02/clip-raster-using-shapefile.html. Args: geo_t: A gdal geoMatrix (ds.GetGeoTransform(). ...
def pprint(l): """Pretty print Parameters: l (list/float/None): object to print Returns: pretty print str """ if isinstance(l, list): if len(l) == 0: return None else: if l == None: return None else: return '%.2f' % l
def speed_round(kmh, delay, round_sec): """ Calculates speed in meters per game round # How many meters zombies move in 5 sec game round at speed 1kmh ? # How many meters per second is 1 kilometer per hour = 1000 in 3600 = 10m in 36s = 10/36 in 1s = 10/36*5 in 1 round = 1.38m per round(5sec) # 1kmh...
def join_urls(*urls) -> str: """Join multiple URL fragments together. Args: urls (List[str]): List of URL fragments to join Returns: str: URL joining result """ if len(urls) == 0: raise ValueError('No URLs to join') leading = '\\' if urls[0][0] == '\\' else '' trai...
def get_log_info(prefix='', rconn=None): """Return info log as a list of log strings, newest first. On failure, returns empty list""" if rconn is None: return [] # get data from redis try: logset = rconn.lrange(prefix+"log_info", 0, -1) except: return [] if logset: ...
def split_quantizer_str(quantizer_str): """ Splits a quantizer string into its components. Interprets the first entry as the quantizer name. Args: quantizer_str: String in the form: "quantizer_type,argument_1,argument_2,..." Returns: Tupel of strings in the form (quantizer_type, [arg...
def validate_markup(markup, query_factory): """Checks whether the markup text is well-formed. Args: markup (str): The marked up query text query_factory (QueryFactory): An object which can create queries Returns: bool: True if the markup is valid """ del markup del quer...
def cbrt(x): """ cbrt(x) = x^{1/3}, if x >= 0 = -|x|^{1/3}, if x < 0 """ if x >= 0: return pow(x, 1.0/3.0) else: return -pow(abs(x), 1.0/3.0)
def get_request_kwargs(useragent, **kwargs): """This Wrapper method exists b/c some values in req_kwargs dict are methods which need to be called every time we make a request """ kv = kwargs.copy() kv['headers'] = kv.get('headers', {'User-Agent': useragent}) kv['proxies'] = kv.get('proxies', Non...
def build_acs_action(action, xml=True): """ Returns a string similar to x-akamai-acs-action:version=1&action=du&format=xml' """ acs_action = 'x-akamai-acs-action:version=1&action={0}'.format(action) acs_action = acs_action + '&format=xml' if xml else acs_action return acs_action
def check_contains(line, name): """ Check if the value field for REQUIRE_DISTRO contains the given name. @param name line The REQUIRE_DISTRO line @param name name The name to look for in the value field of the line. """ try: (label, distros) = line.split(":") return name in distros.split() except ...
def Slides_at(self, slide_index=None, slide_id=None): """ """ slide = None if slide_index is not None: if isinstance(slide_index, int): if slide_index < 0: slide_index += len(self) if 0 <= slide_index < len(self): slide = self[slide_index] elif slide_id is not None:...
def chop(x, n=2): """Chop sequence into n approximately equal slices >>> chop(range(10), n=3) [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9]] >>> chop(range(3), n=10) [[], [0], [], [], [1], [], [], [], [2], []] """ x = list(x) if n < 2: return [x] def gen(): m = len(x) / n ...
def quote_unescape(value, lf='&mjf-lf;', quot='&mjf-quot;'): """ Unescape a string escaped by ``quote_escape``. If it was escaped using anything other than the defaults for ``lf`` and ``quot`` you must pass them to this function. >>> quote_unescape("hello&wobble;'&fish;", '&fish;', '&wobble;') ...
def _checker(word: dict): """checks if the 'word' dictionary is fine :param word: the node in the list of the text :type word: dict :return: if "f", "ref" and "sig" in word, returns true, else, returns false :rtype: bool """ if "f" in word and "ref" in word and "sig" in word: return...
def get_index_dict(input_data): """ Create index - word/label dict from list input @params : List of lists @returns : Index - Word/label dictionary """ result = dict() vocab = set() i = 1 # Flatten list and get indices for element in [word for sentence in input_data for word in s...
def exist(dic, edge): """ check if any part of edge is used """ if edge not in dic.keys(): return False if len(dic[edge]) > 0: return True return False
def add_prefix_to_given_url(url): """ Args: url (str) : the given url argument Returns: the given url argument with a prefix of http:// """ if not url.startswith('http://') and not url.startswith('https://'): if url.startswith('www.'): url = "http...
def validateFilename(value): """ Validate filename with list of points. """ if 0 == len(value): raise ValueError("Filename for list of points not specified.") return value
def list(elements, ordered=False, startIndex=1): """ Create an RST List from a collection. :param elements: (list) a collection of strings, each an element of the list :param ordered: (bool) set's list type between bulleted and enumerated :param startIndex: (int) if...
def string_quote(string): """quote a string for use in search""" return "\""+string.replace("\\","\\\\").replace("\"","\\\"")+"\""
def load_room(name): """ There is a potential security problem here. Who gets to set name? Can that expose a variable? """ return globals().get(name)
def selectByMatchingPrefix(param, opts): """ Given a string parameter and a sequence of possible options, returns an option that is uniquely specified by matching its prefix to the passed parameter. The match is checked without sensitivity to case. Throws IndexError if none of opts starts with par...
def number_spiral_diagonals(limit): """Finds it the diagonals numbers on a n x n spiral""" spiral = [1] number = 1 for i in range(2, limit, 2): for _ in range(0, 4): number += i spiral.append(number) return spiral
def x2bool(s): """Helper function to convert strings from the config to bool""" if isinstance(s, bool): return s elif isinstance(s, str): return s.lower() in ["1", "true"] raise ValueError()
def avg_of_neighbors(mat): """ Return matrix with elements set to the average of their neighbors. """ avgmat = [] for r in range(len(mat)): avgrow = [] for c in range(len(mat[0])): sum, count = 0, 0 if r > 0: sum += mat[r - 1][c] ...
def namify(idx): """ Helper function that pads a given file number and return it as per the dataset image name format. """ len_data = 6 #Ilsvr images are in the form of 000000.JPEG len_ = len(str(idx)) need = len_data - len_ assert len_data >= len_, "Error! Image idx being fetched is incorr...
def get_overwrite_no_response_dto(claim: dict, higher_level_node: str, higher_level: int) -> dict: """Get the DTO for updating a claim request which has an expired node Args: claim: Actual stored claim object to update higher_level_node: id of the node to replace higher_level: dragonchai...
def validate_email_destination(os_mailbox, os_email): """ return True iff O.S. mailbox record is a destination linked to given O.S. email record """ destinations = os_email.get('destinations', None) return os_mailbox['id'] in destinations
def reverse_list_dictionary(to_reverse, keys): """Transforms a list of dictionaries into a dictionary of lists. Additionally, if the initial list contains None instead of dictionaries, the dictionnary will contain lists of None. Mainly used in the measure.py file. Args: to_reverse (list): ...
def mev_to_joule(mev): """ Convert Mega electron Volt(mev) to Joule How to Use: Give arguments for mev parameter *USE KEYWORD ARGUMENTS FOR EASY USE, OTHERWISE IT'LL BE HARD TO UNDERSTAND AND USE.' Parameters: mev (int): nuclear energy in M...
def compile_ingredients(dishes): """ :param dishes: list of dish ingredient sets :return: set This function should return a `set` of all ingredients from all listed dishes. """ new_set = set() for myset in dishes: new_set = new_set.union(myset) return set(new_set)
def removeDuplicates(li: list) -> list: """ Removes Duplicates from history file Args: li(list): list of history entries Returns: list: filtered history entries """ visited = set() output = [] for a, b, c, d in li: if b not in visited: visited.add(b)...
def isinteger(astring): """Is the given string an integer?""" try: int(astring) except ValueError: return False else: return True
def mystery_2b_if(n: int) -> bool: """Mystery 2b.""" if n % 2 == 0: if n % 3 == 1: return True else: return False elif n <= 4: if n < 0: return True else: return False else: if n % 3 == 1: return False ...
def are_cmddicts_same(dict1, dict2): """ Checks to see if two cmddicts are the same. Two cmddicts are defined to be the same if they have the same callbacks/ helptexts/children/summaries for all nodes. """ # If the set of all keys are not the same, they must not be the same. if set(dict1.keys()) != s...
def get_points(json_file): """ Returns json_files points @param: json_file - given json file """ try: return int(json_file['points']) except KeyError: return 0
def ReadList( infile, column = 0, map_function = str, map_category = {} ): """read a list of values from infile. Use map_function to convert values. Use map_category, to map read values directory """ m = [] errors = [] for l in infile: if l[0] == "#": continue try: ...
def dedup_commands(command_list): """ Deduplicate a command list. Now it only removes repeated commands. """ cmd_set = set() deduped_cmd_list = [] for command in command_list: if command.lower() not in cmd_set: cmd_set.add(command.lower()) deduped_cmd_list.app...
def intersection(str1, str2): """ Finds the intersection of str1 and str2 where an intersection is determined by str1[i] == str[i]. >>> intersection("bbbaabbb", "dddaaddd") 'aa' >>> intersection("bbbaabbb", "dddaa") 'aa' >>> intersection("bbbaabbb", "ddd") '' >>> intersection("b...
def savefile(command): """Create savefile-name. If there's no valid name ending with .save, default.save used. Args: command: string containing the player's last command Modifies: nothing Returns: string: complete filename with extension """ sf = "default" for com...
def areListsEqual(l1, l2): """ Check if two lists are equal to each other - have the same elements in the same order """ same = (len(l1) == len(l2)) if same: for i, r in enumerate(l1): same = (l2[i] == r) if not same: break return same
def _is_mxp_header(line): """Returns whether a line is a valid MXP header.""" line = line.strip() return (len(line) > 2 and line.startswith('*') and line.endswith('*') and line[1:-1].strip().lower().startswith('exported from'))
def get_variantid_from_clinvarset(elem): """ Gets variant ID from a ClinVarSet Element :param elem: ClinVarSet :return: Variant ID """ try: # return elem.xpath("ReferenceClinVarAssertion//MeasureSet[@Type='Variant']")[0].attrib['ID'] if elem.find('ReferenceClinVarAssertion...
def get_duration(times): """ Finds and returns the duration of the ECG in units of seconds. :param times: List of time data :return: Float representing duration of ECG data """ return max(times) - min(times)
def highestMax(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the N metrics with the highest maximum value in the time period specified. Example: .. code-block:: none &target=highestMax(server*.instance*.t...
def levenshtein(s1, s2): """ The levensteins distance of two strings. """ s1 = s1.lower() s2 = s2.lower() if len(s1) < len(s2): return levenshtein(s2, s1) if len(s2) == 0: return len(s1) previous_row = list(range(len(s2) + 1)) for i, c1 in enumerate(s1): curre...
def merge_trials(trial_results): """ Merges all provided trial results :param trial_results: A list of trial result objects :return: A new trial result object """ d = {} for tr in trial_results: for k in tr: item = tr[k] if k in d: ...
def bytes_from_str(s: str): """ Convert string to bytes """ return s.encode()
def recent_date(**kwargs): """Select a recent date range for a location selector. :keyword resolution: One keyword time resolution specifier, e.g. ``hours`` or ``days``. :type resolution: int >>> recent_date(months=6) {'recent': {'months': 6}} >>> recent_date(weeks=3) {'recent': {'...
def find_schema_links(resource_type, schemas): """ returns a dict with schema and paths pointing to resource_type e.g. find_schema_links("person", schemas) should return: { "software": [ [ "contributors", "foreignKey" ] ] },...
def safe_unichr(intval): """Create a unicode character from its integer value. In case `unichr` fails, render the character as an escaped `\\U<8-byte hex value of intval>` string. Parameters ---------- intval : int Integer code of character Returns ------- string Unicod...
def as_number(as_number_val: str) -> int: """Convert AS Number to standardized asplain notation as an integer.""" as_number_str = str(as_number_val) if "." in as_number_str: big, little = as_number_str.split(".") return (int(big) << 16) + int(little) else: return int(as_number_st...
def negate_condition(condition): """Negates condition. """ return "not ({0})".format(condition)
def ode_schnakenberg(t, y, a_prod, b_prod): """Derivatives to be called into solve_ivp This returns an array of derivatives y' = [A', B'], for a given state [A, B] at a time t. This is based on the classical Schnakenberg system. Params: t [float] - the time at which the derivative is eval...
def get_value(initial_value): """Get the percentage directly Some values can contain statistical symbols so we ignore them See https://ec.europa.eu/eurostat/statistics-explained/index.php?title=Tutorial:Symbols_and_abbreviations Args: initial_value (string): Raw value Returns: doub...
def sound_speed(p, d, g): """ Calculates the speed of sound Input: p - Pressure d - Density g - Adiabatic index """ import math return math.sqrt(g*p/d)
def get_reward(config: dict) -> float: """ Ensures that the tasks have a reward and estimated time in accordance with the configuration. """ # Make sure that props either defines at least an estimated time + # rewardrate or a reward. assert 'Reward' in config or ('EstimatedTime' in config an...
def calculate(action, a, b): """ Calculate the result of the action and the two numbers. """ print(f'{action}ing a = {a} and b = {b}') if action == 'add': return a + b elif action == 'subtract': return a - b elif action == 'multiply': return a * b elif action =...
def island(matrix): """ given a two by two matrix, get the number of islands in it, an island is a series of 1's connected in a row or a column """ if (not matrix) or len(matrix) == 0: return 0 number_of_islands = 0 l = [True] * len(matrix[0]) for i in range(len(matrix)): ...
def associate(first_list, second_list, offset=0.0, max_difference=0.02): """ Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim to find the closest match for every input tuple. Input: first_list -- first dictionary of (stamp,data) tuples second_list ...
def Lorentz_pulse(theta): """spatial discretisation of Lorentz pulse with duration time td = 1 """ return 4 * (4 + theta ** 2) ** (-1)
def translate_resourcetypes(url): """ translate urls such as /sources/{uid}/ -> sources/{uid} """ trimmed = url.strip('/') split = trimmed.split('/') if len(split) >= 2: return "{}/{}".format(split[0], split[1].lower()) elif len(split) == 1: return split[0] # It should be literal...
def get_coord_box(centre_x, centre_y, distance): """Get the square boundary coordinates for a given centre and distance""" """Todo: return coordinates inside a circle, rather than a square""" return { 'top_left': (centre_x - distance, centre_y + distance), 'top_right': (centre_x + distance, ...
def sweep_config_err_text_from_jsonschema_violations(violations): """Consolidate violation strings from wandb/sweeps describing the ways in which a sweep config violates the allowed schema as a single string. Parameters ---------- violations: list of str The warnings to render. Returns...
def generate_link(resources): """ Generates a link in the CoRE Link Format (RFC6690). :param resources: Array of resources that should translated into links. Resources are dict, containing a path property and a parameters property. Path is a string and parameters ...
def str_visible_len(s): """ :param str s: :return: len without escape chars :rtype: int """ import re # via: https://github.com/chalk/ansi-regex/blob/master/index.js s = re.sub("[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]", "", s) return len(s)
def mangle(name: str, prefix: str = "", suffix: str = "_original") -> str: """Return mangled name.""" return "{prefix}{name}{suffix}".format(**locals())
def _num_samples(x): """Return number of samples in array-like x.""" if not hasattr(x, '__len__') and not hasattr(x, 'shape'): raise TypeError("Expected sequence or array-like, got %r" % x) return x.shape[0] if hasattr(x, 'shape') else len(x)
def pick_best_base_call( *calls ) -> tuple: """ Pick the best base-call from a list of base calls Example: >>> pick_best_base_call( ('A',32), ('C',22) ) ) ('A', 32) >>> pick_best_base_call( ('A',32), ('C',32) ) ) None Args: calls (generator) : generator/list contai...
def binary2int(binary: str): """Convert binary representation of integer as a string to an integer type""" return int(binary, 2)
def question_json_maker(question_id, question, answer, answer_index=1, question_type='MC', difficulty=1, points=10): """ Generates JSON file for each question. :param question: input question.(str) :param answer: output answer(str or int) :param answer_index: index of the correct answer(int) :pa...
def tag_split(tag): """ Extracts the color information from a Finder tag. """ parts = tag.rsplit('\n', 1) if len(parts) == 1: return parts[0], 0 elif len(parts[1]) != 1 or parts[1] not in '01234567': # Not a color number return tag, 0 else: return parts[0], int(parts...
def nanoToSec(nano): """Convert nanoseconds to seconds""" return int(nano / 10**9)
def bounding_box(points): """ Computes the bounding box of a list of 2D points. :param points: list of (x, y) tuples, representing the points :return: list of four (x, y) tuples, representing the vertices of the bounding box """ xs, ys = zip(*points) x_min = min(xs) x_max = max(xs) ...
def temperature_trans(air_in, fuel_in, ex_out): """ Convert degree celsius to kelvin. Optional keyword arguments: --------------------------- :param air_in: temperature of air coming in to fuel cell(FC) :param fuel_in: temperature of fuel coming into (FC)/ temperature of refo...
def get_amazon_product_id(url: str) -> str: """ Extract the amazon product id from product or review web page :param url: url of product :return: product id """ start = url.find("/dp/") # search pattern for a product url count = 4 if start == -1: start = url.find("/product-revie...
def create_edge(vertex_1, vertex_2, edge_type, strand, edges): """ Creates a new edge with the provided information, unless a duplicate already exists in the 'edges' dict. """ # Check if the edge exists, and return the ID if it does query = ",".join([str(vertex_1), str(vertex_2), edge_ty...
def get_verbose_flag(verbose): """Return verbose flag ' -v' if verbose=True, and empty string otherwise, for programs executed as shell commands. Parameters ---------- verbose: bool Verbose mode Returns ------- verbose_flag: string Verbose flag for shell command ...
def flatten(lst): """ Flatten list of list into """ return sum(lst, [])
def trid(ind): """Trid function defined as: $$ f(x) = \sum_{i=1}^n (x_i - 1)^2 - \sum_{i=2}^n x_i x_{i-1}$$ with a search domain of $-n^2 < x_i < n^2, 1 \leq i \leq n$. The global minimum is $f(x^{*}) = -n(n+4)(n-1)/6$ at $x_i = i(n+1-i)$ for all $i=1,2,...,n$. """ return sum(( (x-1)**2. for x i...
def get_matched_faces(faces): """Return the name and rounded confidence of matched faces.""" return { face["name"]: round(face["confidence"], 2) for face in faces if face["matched"] }
def scale_array(arr, s): """Scale an array by s Parameters: 1. array: a numeric array or list 2. s: scaling factor, real number """ return [a*s for a in arr]
def filterTheDict(dictObj, callback): # DGTEMP - Not useful anymore """ Function copied from https://thispointer.com/python-filter-a-dictionary-by-conditions-on-keys-or-values/ Iterate over all the key value pairs in dictionary and call the given callback function() on each pair. Items for which callbac...
def get_cindex(Y, P): """ ******NOTE****** Now the get_cindex is invalid (order dependent of given pairs). We will use lifelines.utils for """ summ = 0 pair = 0 for i in range(0, len(Y)): for j in range(0, len(Y)): if i != j: if(Y[i] > Y[j])...
def cw2w(cw, e): """Transform from *w* index value to *w* count value, using the *e.css('cd')* (column width) as column measure.""" if cw is None: w = 0 else: gw = e.gw # Overwrite style from here. w = cw * (e.css('cw', 0) + gw) - gw return w
def get_entity_values(entityType, dicts): """ Return string array of entity values for specified type, from the inpout array of entityType dicts """ list=["None"] entityDict = next((item for item in dicts if item["Name"] == entityType), None) if entityDict: list = entityDict["Values"] ...
def literal_size(line: bytes) -> int: """Get length of transferred value :param line: :return: int """ try: return int(line.strip(b'{}')) except ValueError as _: return int(line[line.rfind(b'{')+1:-1])
def remove_original_kw( expansion_list, term, ): """remove_original_kw: removes original keyword from the expanded term Args: expansion_list: list; expanded words Returns: finalTerms: list; expanded words with original kw removed """ finalTerms = [] for words in expansion...
def fib(n): """ O(n) time O(1) space """ first = 0 second = 1 for i in range(2,n+1): tmp = first+second first=second second = tmp return second
def parse_response_list(response): """Handles the parsing of a string response representing a list All responses are sent as strings. In order to convert these strings to their python equivalent value, you must call a parse_response_* function. Args: response (str): response string to parse an...
def change_wts_structure(pt_wts, dont_touch=[]): """ Utiility for converting the structure of pre-trained weights of HuggingFace roberta-based models into that required by our model. dont_touch: These elements are left unchanged. """ new_wts_struct = {} for k in pt_wts.keys(): ...
def _opts_to_list(opts): """ This function takes a string and converts it to list of string params (YACS expected format). E.g.: ['SOLVER.IMS_PER_BATCH 2 SOLVER.BASE_LR 0.9999'] -> ['SOLVER.IMS_PER_BATCH', '2', 'SOLVER.BASE_LR', '0.9999'] """ import re if opts is not None: ...
def join_paths(*args) -> str: """Collect given paths and return summary joined absolute path. Also calculate logic for `./` starting path, consider it as "from me" relative point. """ summary_path = "" for path in args: # Check if path starts from slash, to remove it to avoid errors...
def get(obj, path): """ Looks up and returns a path in the object. Returns None if the path isn't there. """ for part in path: try: obj = obj[part] except(KeyError, IndexError): return None return obj
def get_url_from_deploy_stdout(stdout): """Return ELB url from deployment stdout""" loadbalancer_endpoint = None for index, message in enumerate(stdout): if '"Url":' in message: loadbalancer_endpoint = ( stdout[index].strip().replace('"Url": ', '').replace('"', '') ...
def get_decision(criteria, node_idx, tree_struct): """ Define the splitting criteria Args: criteria (str): Growth criteria. node_idx (int): Index of the current node. tree_struct (list) : list of dictionaries each of which contains meta information about each node of the tre...
def _convert_platform_to_chromiumdash_platform(platform): """Converts platform to Chromium Dash platform. Note that Windows in Chromium Dash is win64 and we only want win32.""" platform_lower = platform.lower() if platform_lower == 'windows': return 'Win32' return platform_lower.capitalize()
def mode(data): """ Uses counting sort to figure out the mode. """ count = [0]*(max(data)+1) for i in data: count[i] += 1 return count.index(max(count))
def divide_n_among_bins(n, bins): """ >>> divide_n_among_bins(12, [1, 1]) [6, 6] >>> divide_n_among_bins(12, [1, 2]) [4, 8] >>> divide_n_among_bins(12, [1, 2, 1]) [3, 6, 3] >>> divide_n_among_bins(11, [1, 2, 1]) [2, 6, 3] >>> divide_n_among_bins(11, [.1, .2, .1]) [2, 6, 3] ...