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(). x: x coordinate in map units. y: y coordinate in map units. buffer_size: Optionally specify a buffer size. This is used when a buffer has been applied to extend all edges of an image, as in rasterizeShapfile(). Returns: A tuple with pixel/line locations for each input coordinate. """ ulX = geo_t[0] - buffer_size ulY = geo_t[3] + buffer_size xDist = geo_t[1] yDist = geo_t[5] pixel = (x - ulX) / xDist line = (y - ulY) / yDist return (pixel, line)
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 = 1000m in 3600 seconds = 1000 in 720 game rounds = 1000/720m in 1 round = 1.38m per round(5sec) # answer is = 1.38m/round, so if zombies have speed 3.22kmh their game speed is 3.22 * 1.38mpr = 4.44 meters per 5 second round :param kmh: speed in kilometers per hour :param delay: delay caused by some stuff eg besieging houses, kmh=1/delay :param round_sec: length of game round/iteration per second :return: float (speed in meters per game iteration/round) """ speed = (kmh * 1000 / 3600) / delay * round_sec return speed
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 '' trailing = '\\' if urls[-1][-1] == '\\' else '' return leading + ('/'.join(u.strip('/') for u in urls)) + trailing
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: loglines = [ item.decode('utf-8') for item in logset ] else: return [] loglines.reverse() return loglines
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, [argument_1, argument_2,...]) """ quantizer_type='' args=[] tokens = quantizer_str.split(',') if len(tokens) > 0: quantizer_type=tokens[0] if len(tokens) > 1: args=tokens[1:] return (quantizer_type, args)
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 query_factory return NotImplemented
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', None) cb = kv['proxies'] if callable(cb): kv['proxies'] = cb() kv['allow_redirects'] = True return kv
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 ValueError as e: raise ValueError("Error splitting REQUIRE_DISTRO line: %s" % e)
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: slide = self.get(int(slide_id)) return slide
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 i = 0 for _ in range(n-1): yield x[round(i):round(i + m)] i += m yield x[round(i):] return list(gen())
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;') 'hello"\\'\\n' >>> quote_unescape('hello') 'hello' >>> quote_unescape('hello&mjf-lf;') 'hello\\n' >>> quote_unescape("'hello'") "'hello'" >>> quote_unescape('hello"') 'hello"' >>> quote_unescape("hello&mjf-quot;'") 'hello"\\'' >>> quote_unescape("hello&wobble;'&fish;", '&fish;', '&wobble;') 'hello"\\'\\n' """ return value.replace(lf, '\n').replace(quot, '"')
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 True return False
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 sentence]: if element not in vocab: result[i]=element i+=1 vocab.add(element) return result
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://" + url else: url = "http://www." + url # disable-secrets-detection return url
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 start index is 1 then an auto-enumerated list is used ("#. element\\\n") >>> list(['foo', 'bar']) '- foo\\n- bar\\n' >>> list(['foo', 'bar'], ordered=True) '#. foo\\n#. bar\\n' >>> list(['foo', 'bar'], ordered=True, startIndex=3) '3. foo\\n4. bar\\n' startIndex has no effect if not ordered >>> list(['foo', 'bar'], ordered=False, startIndex=3) '- foo\\n- bar\\n' """ retVal = '' index = startIndex for element in elements: if ordered and startIndex==1: retVal += '#. %s\n' % (element) elif ordered and startIndex>1: retVal += '%s. %s\n' % (index, element) index = index + 1 else: retVal += '- %s\n' % element return retVal
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 param, or if multiple opts start with param. >> selectByMatchingPrefix("a", ["aardvark", "mongoose"]) "aardvark" """ lparam = param.lower() hits = [opt for opt in opts if opt.lower().startswith(lparam)] nhits = len(hits) if nhits == 1: return hits[0] if nhits: raise IndexError("Multiple matches for for prefix '%s': %s" % (param, hits)) else: raise IndexError("No matches for prefix '%s' found in options %s" % (param, opts))
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] count += 1 if r < len(mat) - 1: sum += mat[r + 1][c] count += 1 if c > 0: sum += mat[r][c - 1] count += 1 if c < len(mat[0]) - 1: sum += mat[r][c + 1] count += 1 count = count if count != 0 else 1 avgrow.append(sum / count) avgmat.append(avgrow) return avgmat
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 incorrect. Invalid value." pad = '0'*need return pad+str(idx)
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: dragonchain level of the node to replace Returns: DTO to send to matchmaking in order to update the claim """ return {"claim": claim, "dc_id": higher_level_node, "level": higher_level}
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): List to reverse, should contain dictionaries (or None) keys (list): Keys of the dictionaries inside the list. Returns: Dictionary. """ if to_reverse[0] is None: to_reverse = {k: [None for _ in range(len(to_reverse))] for k in keys} else: to_reverse = {k: [to_reverse[n][k] for n in range(len(to_reverse))] for k in keys} return to_reverse
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 Mega electron Volt Returns: int: the value of nuclear energy in Joule """ joule = mev * (10 ** 6) * (1.6 * 10 ** -19) return joule
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) output.append((a, b, c, d)) return output
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 else: return True
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()) != set(dict2.keys()): return False # Everything in dict1 should be in dict2 for key in dict1: # Check everything except children; Check for children recursively for propertytype in dict1[key]: if (not propertytype in dict2[key] or dict1[key][propertytype] != dict2[key][propertytype]): return False # Check children if not are_cmddicts_same(dict1[key]['children'], dict2[key]['children']): return False return True
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: d = map_function(l[:-1].split("\t")[column]) except ValueError: continue try: if map_category: d = map_category[d] except KeyError: errors.append( d ) continue m.append(d) return m, errors
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.append(command) return deduped_cmd_list
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("bbbbbbbbb", "ababababa") 'bbbb' >>> intersection("bbbaabbb", 1) Traceback (most recent call last): ... AssertionError # My doctests >>> intersection('aaabbbccc', 'bbbcccaaa') '' >>> intersection('2345', '12358459374ffdhk~!#*') '5' >>> intersection('#RELATABLE!', '#relatable!') '#!' """ assert isinstance(str1, str) assert isinstance(str2, str) return ''.join([str1[i] \ for i in range(0, min([len(str1), len(str2)])) if str1[i] == str2[i]])
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 in command: if com.endswith(".save"): sf = com.split(".")[0] break return sf
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').find('MeasureSet') is not None: out = elem.find('ReferenceClinVarAssertion').find('MeasureSet').attrib['ID'] elif elem.find('ReferenceClinVarAssertion').find('GenotypeSet') is not None: out = elem.find('ReferenceClinVarAssertion').find('GenotypeSet').find('MeasureSet').attrib['ID'] else: out = '' return out except: return ''
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*.threads.busy,5) Draws the top 5 servers who have had the most busy threads during the time period specified. """ result_list = sorted( seriesList, key=lambda s: max(s) )[-n:] return sorted(result_list, key=lambda s: max(s), reverse=True)
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): current_row = [i + 1] for j, c2 in enumerate(s2): # j+1 instead of j since previous_row and current_row are one character longer: insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 # than s2 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
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: d[k][0] += item[0] d[k][1] += item[1] else: d[k] = item[:] return 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': {'weeks': 3}} """ if not len(kwargs) == 1: raise ValueError('Must specify a single date resolution') resolution = list(kwargs.keys())[0] value = list(kwargs.values())[0] if resolution not in ('minutes' 'hours' 'days' 'weeks' 'months' 'years'): raise ValueError('Invalid date resolution: %s' % resolution) payload = {'recent': {resolution: value}} return payload
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" ] ] }, Because software->contributors->foreignKey is a link to a person. """ def parse_property(property, foreign_resource_type, path, results): if len(path) > 0 and path[-1] == 'foreignKey' and property['properties']['collection']['enum'][0] == foreign_resource_type: results.append(path) elif "properties" in property: # has sub properties for property_name in property['properties']: parse_property( property['properties'][property_name], foreign_resource_type, path[:] + [property_name], results ) elif property.get('type') == 'array': parse_property( property['items'], foreign_resource_type, path, results ) results = {} for schema_name in schemas.keys(): schema = schemas[schema_name] if '$schema' in schema: # filters out weird stuff like software_cache result = [] parse_property(schema, resource_type, [], result) if len(result) > 0: results[schema_name] = result return results
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 Unicode string of character """ try: return chr(intval) except ValueError: # ValueError: chr() arg not in range(0x10000) (narrow Python build) s = "\\U%08x" % intval # return UTF16 surrogate pair return s.decode('unicode-escape')
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_str)
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 evaluated y [array] - the current state of the system, in the form [A, B] """ return [y[0]**2 * y[1] - y[0] + a_prod, -y[0]**2 * y[1] + b_prod]
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: double: Percentage """ value = initial_value if ':' in value: return None elif 'b' in value: value = value.split(" ")[0] return value
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 and 'RewardRate' in config), \ "Expected to find either a Reward or RewardRate and EstimatedTime in config" if 'Reward' in config: return config['Reward'] else: return config['EstimatedTime'] * config['RewardRate'] / 3600
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 == 'divide': return a / b
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)): ind = True for j in range(len(matrix[0])): if matrix[i][j] == 0: l[j] = False ind = False if ind: number_of_islands += 1 return number_of_islands + sum(l)
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 -- second dictionary of (stamp,data) tuples offset -- time offset between both dictionaries (e.g., to model the delay between the sensors) max_difference -- search radius for candidate generation Output: matches -- list of matched tuples ((stamp1,data1),(stamp2,data2)) """ first_keys = list(first_list.keys()) second_keys = list(second_list.keys()) potential_matches = [(abs(a - (b + offset)), a, b) for a in first_keys for b in second_keys if abs(a - (b + offset)) < max_difference] potential_matches.sort() matches = [] for diff, a, b in potential_matches: if a in first_keys and b in second_keys: first_keys.remove(a) second_keys.remove(b) matches.append((a, b)) matches.sort() return matches
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 literally impossible for the following to happen else: # pragma: no cover return ''
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, centre_y + distance), 'bottom_left': (centre_x - distance, centre_y - distance), 'bottom_right': (centre_x + distance, centre_y - 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 ------- violation: str The consolidated violation text. """ violation_base = ( "Malformed sweep config detected! This may cause your sweep to behave in unexpected ways.\n" "To avoid this, please fix the sweep config schema violations below:" ) for i, warning in enumerate(violations): violations[i] = " Violation {}. {}".format(i + 1, warning) violation = "\n".join([violation_base] + violations) return violation
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 is a dict, containing the parameters and their values. """ links = "" for i, resource in enumerate(resources): link = "<" + resource["path"] + ">" if "parameters" in resource: for parameter in resource["parameters"]: link += ";" + str(parameter) + "=" + str(resource["parameters"][parameter]) links += link if i != len(resources) - 1: links += "," return links
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 containing tuples Returns: tuple (best_base, best_q) or ('N',0) when there is a tie """ # (q_base, quality, ...) best_base, best_q = None, -1 tie = False for call in calls: if call is None: continue if call[1]>best_q: best_base= call[0] best_q=call[1] tie=False elif call[1]==best_q and call[0]!=best_base: tie=True if tie or best_base is None: return ('N',0) return best_base, best_q
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) :param question_type: type of question ex: MC (Multiple Choice).(str) :param difficulty: difficulty level of the question(1 to 5)(int) :param points : points for each right answer. (int) :return: a question.(JSON) """ questions_template = { "questionID": question_id, "question": question, "questionType": question_type, "answerSelectionType": "single", "answers": answer, "correctAnswer": answer_index, "messageForCorrectAnswer": "Correct Answer", "messageForIncorrectAnswer": "Incorrect Answer", "difficulty": difficulty, "point": points } return questions_template
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[1])
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) y_min = min(ys) y_max = max(ys) return [(x_min, y_min), (x_max, y_min), (x_max, y_max), (x_min, y_max)]
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 reformer :param ex_out: temperature of exhaust coming out of FC :return: return the degree of kelvin """ T_FC_air_in = air_in + 273.15 T_FC_fuel_in = fuel_in + 273.15 T_FC_ex_out = ex_out + 273.15 return [T_FC_air_in, T_FC_fuel_in, T_FC_ex_out]
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-reviews/") # search pattern for a review page count = 17 if start == -1: start = url.find("/product/") # search pattern for a review page count = 9 if start == -1: raise Exception( "Failed to find the product id in the given url: " + url ) end = url.find("/", start + count) if end == -1: end = url.find("?", start + count) if end == -1: end = len(url) result = url[start + count : end] return result
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_type,strand]) if query in edges.keys(): existing_edge_id = edges[query][0] return existing_edge_id, edges # In the case of no match, create the edge # Get ID number from counter edge_id = edges["counter"] + 1 edges["counter"] += 1 new_edge = (edge_id, vertex_1, vertex_2, edge_type, strand) keyname = ",".join([str(vertex_1), str(vertex_2), edge_type, strand]) edges[keyname] = new_edge return edge_id, edges
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 """ if verbose is True: verbose_flag = ' -v' else: verbose_flag = '' return verbose_flag
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 in ind)) - sum(( ind[i] * ind[i-1] for i in range(1, len(ind)) )),
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 callback() returns True, add them to the new dictionary. In the end return the new dictionary.""" newDict = dict() # Iterate over all the items in dictionary for (key, value) in dictObj.items(): # Check if item satisfies the given condition then add to new dict if callback((key, value)): newDict[key] = value return newDict
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]): pair +=1 summ += 1* (P[i] > P[j]) + 0.5 * (P[i] == P[j]) if pair != 0: return summ/pair else: return 0
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"] return list
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_list: split_terms = words.split(" ") tmpList = [x for x in split_terms if x != term] tmpList = [" ".join(tmpList)] finalTerms = finalTerms + tmpList return finalTerms
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 and convert to proper value Returns: (list): returns reponse string converted to list """ element_sep = ";;" parsed_response = response.split(element_sep) return parsed_response
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(): if k in dont_touch: new_wts_struct[k] = pt_wts[k] continue nested_modules = k.split('/') second_last_module = '/'.join(nested_modules[:-1]) last_module = nested_modules[-1] if last_module=='weight': last_module = 'w' elif last_module =='bias': last_module = 'b' if second_last_module not in new_wts_struct: new_wts_struct[second_last_module] = {} new_wts_struct[second_last_module][last_module] = pt_wts[k] return new_wts_struct
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: list_opts = re.split('\s+', opts) return list_opts return ""
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 if path[0] == "/": path = path[1:] # Check if path given in logical form (starts from "./") elif path[:2] == "./": # Remove leading "./" to perform proper paths joining path = path[2:] # Check if path ends with slash, to remove it to avoid errors if path[len(path)-1] == "/": path = path[:len(path)-1] summary_path += "/" + path return summary_path
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('"', '') ) return loadbalancer_endpoint
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 tree. Returns: The function returns one of the following strings 'split': split the node 'extend': extend the node 'keep': keep the node as it is """ if criteria == 'always': # always split or extend if tree_struct[node_idx]['valid_accuracy_gain_ext'] > tree_struct[node_idx]['valid_accuracy_gain_split'] > 0.0: return 'extend' else: return 'split' elif criteria == 'avg_valid_loss': if tree_struct[node_idx]['valid_accuracy_gain_ext'] > tree_struct[node_idx]['valid_accuracy_gain_split'] and \ tree_struct[node_idx]['valid_accuracy_gain_ext'] > 0.0: print("Average valid loss is reduced by {} ".format(tree_struct[node_idx]['valid_accuracy_gain_ext'])) return 'extend' elif tree_struct[node_idx]['valid_accuracy_gain_split'] > 0.0: print("Average valid loss is reduced by {} ".format(tree_struct[node_idx]['valid_accuracy_gain_split'])) return 'split' else: print("Average valid loss is aggravated by split/extension." " Keep the node as it is.") return 'keep' else: raise NotImplementedError( "specified growth criteria is not available. ", )
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] """ total = sum(bins) acc = 0.0 out = [] for b in bins: now = n / total * b + acc now, acc = divmod(now, 1) out.append(int(now)) return out