content
stringlengths
42
6.51k
def bytesto(bytes, to, bsize=1024): """convert bytes to megabytes, etc. sample code: print('mb= ' + str(bytesto(314575262000000, 'm'))) sample output: mb= 300002347.946 """ a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 } r = float(bytes) for i in range(a[to]): r = r / bsize return(r)
def _checkplatform(platform): """ Check if the platform is valid. :param platform: The platform to check. """ if platform == 'origin' or platform == 'psn' or platform == 'xbl': return True else: return False
def travel_object(obj, key_functions=[], val_functions=[]): """Recursively apply functions to the keys and values of a dictionary Parameters ---------- obj : dict/list List or dict to recurse through. key_functions : list Functions to apply to the keys in 'obj'. val_functions : list Functions to apply to the values in 'obj' Returns ------- list/dict A list or dict in which all nested keys and values have been altered by the key_functions and val_functions respectively. """ def operate_on_dict(the_dict): new_dict = {} for key, val in the_dict.items(): new_key = key for key_func in key_functions: new_key = key_func(new_key) if isinstance(val, dict) or isinstance(val, list): new_val = travel_object(val, key_functions=key_functions, val_functions=val_functions) else: new_val = val for val_func in val_functions: new_val = val_func(val) new_dict[new_key] = new_val return new_dict if isinstance(obj, list): new_list = [] for item in obj: new_item = operate_on_dict(item) if isinstance(item, dict) else item new_list.append(new_item) return new_list elif isinstance(obj, dict): altered_dict = operate_on_dict(obj) return altered_dict else: err_msg = 'Invalid type: the passed "obj" argument was not of type "dict" or "list".' raise TypeError(err_msg)
def info_header(label): """Make a nice header string.""" return "--{0:-<60s}".format(" "+label+" ")
def remove_empty_items(dict_obj: dict): """Remove null values from a dict.""" return {k: v for k, v in dict_obj.items() if v is not None}
def is_not_null(value): """ test for None and empty string :param value: :return: True if value is not null/none or empty string """ return value is not None and len(str(value)) > 0
def _aggregate_nomad_jobs(aggregated_jobs): """Aggregates the job counts. This is accomplished by using the stats that each parameterized job has about its children jobs. `jobs` should be a response from the Nomad API's jobs endpoint. """ nomad_running_jobs = {} nomad_pending_jobs = {} for (aggregate_key, group) in aggregated_jobs: pending_jobs_count = 0 running_jobs_count = 0 for job in group: if job["JobSummary"]["Children"]: # this can be null pending_jobs_count += job["JobSummary"]["Children"]["Pending"] running_jobs_count += job["JobSummary"]["Children"]["Running"] nomad_pending_jobs[aggregate_key] = pending_jobs_count nomad_running_jobs[aggregate_key] = running_jobs_count return nomad_pending_jobs, nomad_running_jobs
def get_distances(s1, s2): """Returns the distances from every atom to every other in the given set""" distances = [] for a in s1: for b in s2: x, y, p = a.x - b.x, a.y - b.y, a.neg != b.neg distances.append(((x, y, p), (a, b))) return distances
def _merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z
def cast_tweet_id(tweet_id: str) -> int: """Cast a single Tweet ID to int. They may be prefixed with 'ID:' so try to remove this. """ if tweet_id.lower().startswith('id:'): tweet_id = tweet_id.lower()[3:] return int(tweet_id)
def attrgetter(x, attr): """Attrgetter as a function for verb This is helpful when we want to access to an accessor (ie. CategoricalAccessor) from a SeriesGroupBy object """ return getattr(x, attr)
def startOfInterval(time_ts, interval): """Find the start time of an interval. This algorithm assumes unit epoch time is divided up into intervals of 'interval' length. Given a timestamp, it figures out which interval it lies in, returning the start time. time_ts: A timestamp. The start of the interval containing this timestamp will be returned. interval: An interval length in seconds. Returns: A timestamp with the start of the interval. Examples: >>> os.environ['TZ'] = 'America/Los_Angeles' >>> time.tzset() >>> start_ts = time.mktime(time.strptime("2013-07-04 01:57:35", "%Y-%m-%d %H:%M:%S")) >>> time.ctime(startOfInterval(start_ts, 300)) 'Thu Jul 4 01:55:00 2013' >>> time.ctime(startOfInterval(start_ts, 300.0)) 'Thu Jul 4 01:55:00 2013' >>> time.ctime(startOfInterval(start_ts, 600)) 'Thu Jul 4 01:50:00 2013' >>> time.ctime(startOfInterval(start_ts, 900)) 'Thu Jul 4 01:45:00 2013' >>> time.ctime(startOfInterval(start_ts, 3600)) 'Thu Jul 4 01:00:00 2013' >>> time.ctime(startOfInterval(start_ts, 7200)) 'Thu Jul 4 01:00:00 2013' >>> start_ts = time.mktime(time.strptime("2013-07-04 01:00:00", "%Y-%m-%d %H:%M:%S")) >>> time.ctime(startOfInterval(start_ts, 300)) 'Thu Jul 4 00:55:00 2013' >>> start_ts = time.mktime(time.strptime("2013-07-04 01:00:01", "%Y-%m-%d %H:%M:%S")) >>> time.ctime(startOfInterval(start_ts, 300)) 'Thu Jul 4 01:00:00 2013' >>> start_ts = time.mktime(time.strptime("2013-07-04 01:04:59", "%Y-%m-%d %H:%M:%S")) >>> time.ctime(startOfInterval(start_ts, 300)) 'Thu Jul 4 01:00:00 2013' >>> start_ts = time.mktime(time.strptime("2013-07-04 00:00:00", "%Y-%m-%d %H:%M:%S")) >>> time.ctime(startOfInterval(start_ts, 300)) 'Wed Jul 3 23:55:00 2013' >>> start_ts = time.mktime(time.strptime("2013-07-04 07:51:00", "%Y-%m-%d %H:%M:%S")) >>> time.ctime(startOfInterval(start_ts, 60)) 'Thu Jul 4 07:50:00 2013' >>> start_ts += 0.1 >>> time.ctime(startOfInterval(start_ts, 60)) 'Thu Jul 4 07:51:00 2013' """ start_interval_ts = int(time_ts / interval) * interval if time_ts == start_interval_ts: start_interval_ts -= interval return start_interval_ts
def humanize_time(secs): """ Convert seconds to hh:mm:ss format. """ secs = int(secs) mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) return '{h:02d}:{m:02d}:{s:02d} (hh:mm:ss)'.format(h=hours, m=mins, s=secs)
def trapezoid_area(base_minor, base_major, height): """Returns the area of a trapezoid""" # You have to code here # REMEMBER: Tests first!!! return ((base_minor + base_major )* height)/2
def bubble_sort(arr): """Refresher implementation of buble-sort - in-place & stable. :param arr: List to be sorted. :return: Sorted list. """ for i in range(len(arr)): for j in range(len(arr) - 1): # check if elements are in relative out-of-order if arr[j] > arr[j + 1]: # swapping adjacent elements arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr
def split_by_group(a, start, end): """Split string a into non-group and group sections, where a group is defined as a set of characters from a start character to a corresponding end character.""" res, ind, n = [], 0, 0 new = True for c in a: if new: res.append("") new = False i = start.find(c) if n == 0: if i >= 0: # Start of new group res.append("") ind = i n += 1 else: if start[ind] == c: n += 1 elif end[ind] == c: n-= 1 if n == 0: new = True res[-1] += c return res
def convtransp_output_shape(h_w,kernel_size=1,stride=1,pad=0,dilation=1): """ Utility function for computing output of transposed convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(h_w) is not tuple: h_w=(h_w,h_w) if type(kernel_size) is not tuple: kernel_size=(kernel_size,kernel_size) if type(stride) is not tuple: stride=(stride,stride) if type(pad) is not tuple: pad=(pad,pad) h=(h_w[0]-1)*stride[0]-2*pad[0]+kernel_size[0]+pad[0] w=(h_w[1]-1)*stride[1]-2*pad[1]+kernel_size[1]+pad[1] return h,w
def make_floats(params): """ pass list of params, return floats of those params (for caching) """ if params is None: return None if hasattr(params, "__len__"): return [float(p) for p in params] else: return float(params)
def convert_tags(tags): """Will convert tags so the article can be uploaded to dev.to. This involves removing the `-` and making the tag lowercase. Args: tags (list): The list of tags to convert. Returns: list: The list of converted tags """ new_tags = [] for tag in tags: converted_tag = tag.replace("-", "").lower() new_tags.append(converted_tag) return new_tags
def parse_home(d): """ Used to parse name of home team. """ return str(d.get("tTNaam", ""))
def create_time_filter(create_time, comparator): """Return a valid createTime filter for operations.list().""" return 'createTime {} "{}"'.format(comparator, create_time)
def parse_concepts(api_concepts): """Parse the API concepts data.""" return {concept['name']: round(100.0*concept['value'], 2) for concept in api_concepts}
def rgb(red, green, blue): """Helper function that returns rgb strings to be used by color-specification headers. Arguments: red (int): Red color value. green (int): Green color value. blue (int): Blue color value. Returns: A string representing the specified color. Example: >>> rgb(23, 167, 42) 'rgb(23, 167, 42)' """ return 'rgb({0:d},{1:d},{2:d})'.format(red, green, blue)
def generate_layer_name(layer_type, index): """ Generates a unique layer name """ # Generating a unique name for the layer return f"{layer_type.lower()}_layer_{index+1}"
def compoundedInterest(fv, p): """Compounded interest Returns: Interest value Input values: fv : Future value p : Principal """ i = fv - p return i
def gather_settings(pre='DJANGO_') -> dict: """ Collect dict of settings from env variables. """ import os return { k[len(pre):]: v for (k, v) in os.environ.items() if k.startswith(pre) }
def catch_start_end(s): """ input string is like: "start_char=2|end_char=8" """ parts = s.split("|") assert len(parts) == 2 start_char = "start_char=" end_char = "end_char=" pre, post = parts[0], parts[1] assert pre.startswith(start_char) assert post.startswith(end_char) start = int(pre[len(start_char):]) end = int(post[len(end_char):]) return start, end
def sizeof_fmt(num, suffix='B'): """ Given `num` bytes, return human readable size. Taken from https://stackoverflow.com/a/1094933 """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def clean_up_spacing(sentence: str) -> str: """ :param sentence: str a sentence to clean of leading and trailing space characters. :return: str a sentence that has been cleaned of leading and trailing space characters. """ return sentence.strip()
def format_ruckus_value(value, force_str=False): """Format a string value into None, int, or bool if possible.""" value = value.strip() if not value: return None if not force_str: if value.isnumeric(): return int(value) if value in ["true", "Enabled", "Yes"]: return True if value in ["false", "Disabled", "No"]: return False return value
def nest_list_to_tuple(nest): """Convert the lists in a nest to tuples. Some tf-agents function (e.g. ReplayBuffer) cannot accept nest containing list. So we need some utitity to convert back and forth. Args: nest (a nest): a nest structure Returns: nest with the same content as the input but lists are changed to tuples """ if isinstance(nest, tuple): new_nest = tuple(nest_list_to_tuple(item) for item in nest) if hasattr(nest, '_fields'): # example is a namedtuple new_nest = type(nest)(*new_nest) return new_nest elif isinstance(nest, list): return tuple(nest_list_to_tuple(item) for item in nest) elif isinstance(nest, dict): new_nest = {} for k, v in nest.items(): new_nest[k] = nest_list_to_tuple(v) return new_nest else: return nest
def _decimal_year_to_mjd2000_simple(decimal_year): """ Covert decimal year to Modified Julian Date 2000. """ return (decimal_year - 2000.0) * 365.25
def the_last_50_entries(list_of_entries): """Simply returns the last 50 entries.""" return list_of_entries[-50:]
def component_col_regex(component_count): """ Match things like 'foo_bar_baz_corge' """ return '_'.join(([r'[^_\s]+'] * component_count))
def get_preferred_media_item_link(item): """ Guess the most useful link for a given piece of embedded media. :param item: a single media object, as decoded JSON :return: the best-guess link to output for optimum IRC user utility :rtype: str Twitter puts just a thumbnail for the media link if it's animated/video. Ideally we'd like clients that support it to show inline video, not a thumbnail, so we need to apply a little guesswork to figure out if we can output a video clip instead of a static image. """ video_info = item.get('video_info', {}) variants = video_info.get('variants', []) if not (video_info and variants): # static image, or unknown other rich media item; return static image return item['media_url_https'] # if we've reached this point, it's probably "real" rich media if len(variants) > 1: # ugh, Twitter returns unsorted data variants.sort(key=lambda k: k.get('bitrate', 0)) return variants[-1]['url']
def int2str(num,l): """ Given an integer num and desired length l, returns the str(num) with appended leading zeroes to match the size l. """ if len(str(num))<l: return (l-len(str(num)))*'0'+str(num) else: return str(num)
def _path_parts(path): """Takes a path and returns a list of its parts with all "." elements removed. The main use case of this function is if one of the inputs to _relative() is a relative path, such as "./foo". Args: path_parts: A list containing parts of a path. Returns: Returns a list containing the path parts with all "." elements removed. """ path_parts = path.split("/") return [part for part in path_parts if part != "."]
def difference(dataset, interval=1): """ Differencing time series according to difference_order/interval dataset: type:list, Desc: list contaning timeseries values interval: type:integers Desc: Differencing order """ def do_diff(dataset): diff = list() for i in range(1, len(dataset)): value = dataset[i] - dataset[i - 1] diff.append(value) return diff diff_list = dataset last_obs_value = [] for _ in range(1, interval + 1): last_obs_value.append(diff_list[0]) diff_list = do_diff(diff_list) return diff_list, last_obs_value
def create_batch_groups(test_groups, batch_size): """Return batch groups list of test_groups.""" batch_groups = [] for test_group_name in test_groups: test_group = test_groups[test_group_name] while test_group: batch_groups.append(test_group[:batch_size]) test_group = test_group[batch_size:] return batch_groups
def escape_parameters(formula, escape_char='_'): """ Escapes the parameters of a category formula. Parameters ---------- formula : str Category formula. escape_char : str, optional Character string to escape parameters with (prepended and appended to variables). Note ---- Currently, the algorithm fails to correctly account for variables starting with a '1'. Examples -------- >>> escape_parameters('a * b * c') '_a_ * _b_ * _c_' >>> escape_parameters('e * ee * a * ea * _ba') '_e_ * _ee_ * _a_ * _ea_ * __ba_' >>> escape_parameters('a1 * a2 * e1a') '_a1_ * _a2_ * _e1a_' """ escaped = '' reading_mode = False for char in formula: if char not in ['*', '(', ')', '+', ' ', '-', '1']: if not reading_mode: escaped += escape_char reading_mode = True if char in ['*', '(', ')', '+', ' ', '-']: if reading_mode: escaped += escape_char reading_mode = False escaped += char if reading_mode: escaped += escape_char return escaped
def parse_version(v): """ Take a string version and conver it to a tuple (for easier comparison), e.g.: "1.2.3" --> (1, 2, 3) "1.2" --> (1, 2, 0) "1" --> (1, 0, 0) """ parts = v.split(".") # Pad the list to make sure there is three elements so that we get major, minor, point # comparisons that default to "0" if not given. I.e. "1.2" --> (1, 2, 0) parts = (parts + 3 * ["0"])[:3] return tuple(int(x) for x in parts)
def inverseDict(d): """ Returns a dictionay indexed by values {value_k:key_k} Parameters: ----------- d : dictionary """ dt={} for k,v in list(d.items()): if type(v) in (list,tuple): for i in v: dt[i]=k else: dt[v]=k return dt
def ircLower(string): """ Lowercases a string according to RFC lowercasing standards. """ return string.lower().replace("[", "{").replace("]", "}").replace("\\", "|")
def g1(a, b): """Returns False eactly when a and b are both True.""" if a == True and b == True: return False else: return True
def symbol_match(sym1, sym2): """ Check whether two symbols match. If one argument is None they always match. :param sym1: symbol 1 :param sym2: symbol 2 :return: whether both symbol (sequences) match. """ if len(sym1) != len(sym2): return False for e1, e2 in zip(sym1, sym2): if not (e1 == e2 or e1 is None or e2 is None): return False return True
def insertion_sort(x): """ Sorts an array x in non-decreasing order using the insertion sort algorithm. @type x: array @param x: the array to sort @rtype: array @return: the sorted array """ if len(x) <= 1: return x for i, v in enumerate(x): j = i while j > 0 and x[j] < x[j - 1]: # Nice python idiom for swapping array elements x[j - 1], x[j] = x[j], x[j - 1] j -= 1 return x
def extra_domain_entries(domfilter, extrafilters): """Return extra queryset filters.""" if domfilter is not None and domfilter and domfilter != 'relaydomain': return {} if "srvfilter" in extrafilters and extrafilters["srvfilter"]: return {"relaydomain__service__name": extrafilters["srvfilter"]} return {}
def stripcomments(line): """From a GROMACS topology formatted line, return (line, comments) with whitespace and comments stripped. Comments are given with ;. Parameters ---------- line : str GROMACS line to be stripped Returns ------- line : str GROMACS line with comments and whitespace (leading/trailing) stripped """ # strip comments index = line.find(';') comments ='' if index > -1: comments = line[index:] line = line[0:index] # strip whitespace line = line.strip() comments = comments.strip() # return stripped line return line,comments
def flatten_deps(deps): """Converts deps.lock dict into a list of go packages specified there.""" out = [] for p in deps['imports']: # Each 'p' here have a form similar to: # # - name: golang.org/x/net # version: 31df19d69da8728e9220def59b80ee577c3e48bf # repo: https://go.googlesource.com/net.git # subpackages: # - context # - context/ctxhttp # # where empty 'subpackages' means an entire repo is used. sub = p.get('subpackages') if not sub: out.append(p['name']) else: out.extend(p['name'] + '/' + subpkg for subpkg in sub) return sorted(out)
def format_bytes(bytes, unit, SI=False): """ Converts bytes to common units such as kb, kib, KB, mb, mib, MB Parameters --------- bytes: int Number of bytes to be converted unit: str Desired unit of measure for output SI: bool True -> Use SI standard e.g. KB = 1000 bytes False -> Use JEDEC standard e.g. KB = 1024 bytes Returns ------- str: E.g. "7 MiB" where MiB is the original unit abbreviation supplied """ if unit.lower() in "b bit bits".split(): return f"{bytes*8} {unit}" unitN = unit[0].upper()+unit[1:].replace("s","") # Normalised reference = {"Kb Kib Kibibit Kilobit": (7, 1), "KB KiB Kibibyte Kilobyte": (10, 1), "Mb Mib Mebibit Megabit": (17, 2), "MB MiB Mebibyte Megabyte": (20, 2), "Gb Gib Gibibit Gigabit": (27, 3), "GB GiB Gibibyte Gigabyte": (30, 3), "Tb Tib Tebibit Terabit": (37, 4), "TB TiB Tebibyte Terabyte": (40, 4), "Pb Pib Pebibit Petabit": (47, 5), "PB PiB Pebibyte Petabyte": (50, 5), "Eb Eib Exbibit Exabit": (57, 6), "EB EiB Exbibyte Exabyte": (60, 6), "Zb Zib Zebibit Zettabit": (67, 7), "ZB ZiB Zebibyte Zettabyte": (70, 7), "Yb Yib Yobibit Yottabit": (77, 8), "YB YiB Yobibyte Yottabyte": (80, 8), } key_list = '\n'.join([" b Bit"] + [x for x in reference.keys()]) +"\n" if unitN not in key_list: raise IndexError(f"\n\nConversion unit must be one of:\n\n{key_list}") units, divisors = [(k,v) for k,v in reference.items() if unitN in k][0] if SI: divisor = 1000**divisors[1]/8 if "bit" in units else 1000**divisors[1] else: divisor = float(1 << divisors[0]) value = bytes / divisor return f"{value:,.0f} {unitN}{(value != 1 and len(unitN) > 3)*'s'}"
def reduce_string(s): """ >>> assert(reduce_string(None) == 'Empty String') >>> assert(reduce_string('') == 'Empty String') >>> assert(reduce_string('abc') == 'abc') >>> assert(reduce_string('aabbc') == 'c') >>> assert(reduce_string('abcc') == 'ab') >>> assert(reduce_string('aabbcc') == 'Empty String') """ if s is None or len(s) == 0: return 'Empty String' stack = [] for char in s: if len(stack) == 0: stack.append(char) continue if char == stack[-1]: stack.pop() else: stack.append(char) return 'Empty String' if len(stack) == 0 else ''.join(stack)
def all_tag_filter(tags): """Return a filter of the element by all the tags for a json post advance search. :param List of :class:`str` tags: Desired filtering tags :returns: json structure to call the asking tasks. """ if not isinstance(tags, list): tags = [tags] if len(tags) == 1: return { "operator": "Equal", "field": "Tags", "value": tags[0] } tag_selector = { "operator": "And", "filters": [ { "operator": "Equal", "field": "Tags", "value": tag_value } for tag_value in tags ] } return tag_selector
def lengthOfLastWord(s): """ :type s: str :rtype: int """ index_list=[i for i in range(len(s)) if s[i] != " "] if not index_list: return 0 for i in range(len(index_list)-1,-1,-1): if index_list[i]-1 != index_list[i-1]: return index_list[-1]-index_list[i]+1
def compare_para_dict(para_dict_old, para_dict_new): """Compare two parameter dictionaries. Parameters ---------- para_dict_old : dictionary old parameter dictionary para_dict_new : dictionary new parameter dictionary Returns ------- status : bool True if same, False if different """ shared_item = set(para_dict_old.items()) & set(para_dict_new.items()) if len(shared_item) == len(para_dict_old): return True else: return False
def pea_reject_image(img): """ Check if PEA would reject image (too narrow, too peaky, etc) """ # To be implemented return False
def get_color_dist(c1, c2): """Calculates the "distance" between two colors, where the distance is another color whose components are the absolute values of the difference between each component of the input colors. """ return tuple(abs(v1 - v2) for v1, v2 in zip(c1, c2))
def flatten_json(nested_json): """ Flatten json object with nested keys into a single level. Args: nested_json: A nested json object. Returns: The flattened json object if successful, None otherwise. """ out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], name + a + '_') elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(nested_json) return out
def generate_dmenu_options(optlist: list) -> str: """ Generates a string from list seperated by newlines. """ return "\n".join(optlist)
def rotate_right(x, y): """ Right rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_right >>> a = [0, 1, 2] >>> rotate_right(a, 1) [2, 0, 1] """ if len(x) == 0: return [] y = len(x) - y % len(x) return x[y:] + x[:y]
def getUser(ctx, *arg): """ returns a user id from either the arguments or if None is passed the sender """ if arg == (): # if no argument is passed go with sender return(ctx.author.id) else: return(arg[0].strip('<!@> '))
def exner(p): """use this to get the exner function exner * potential temperature = real temperature """ Rd=287.058 cp=1003.5 p0=1000.0 try: if p.max()>1200: p0*=100.0 except: if p>1200: p0*=100.0 return (p/p0)**(Rd/cp)
def maxing(corner): """ Return the Limits for the size rigth of the marker. To understand the idea of this you must debug the point returning from the detection marker. Else mantain this method """ x1 = corner[0][0] y1 = corner[0][1] x2 = corner[1][0] y2 = corner[1][1] x3 = corner[2][0] y3 = corner[2][1] x4 = corner[3][0] y4 = corner[3][1] min_x = min([x1, x2, x3, x4]) max_x = max([x1, x2, x3, x4]) max_y = max([y1, y2, y3, y4]) min_y = min([y1, y2, y3, y4]) return min_x, max_x, min_y, max_y
def whoTHIS(msg): """To know who sent the message. 'Self' for yourself, 'Human' for the other *human*. :param msg: unprocessed message :type msg: str :return: Who sent this message :rtype: str :Example: .. code-block:: python whoTHIS(x) *x is an unprocessed message* """ if 'Pos(r) Ta(start)' in msg: return 'Human' if 'Pos(r) Ta(end)' in msg: return 'Self'
def filer_elements(elements, element_filter): """ Ex.: If filtered on elements [' '], ['a', ' ', 'c'] becomes ['a', 'c'] """ return [element for element in elements if element not in element_filter]
def check(local_env): """Validate expected results""" is_success = True if local_env["nativeCallTagA"] != 10 or local_env["nativeCallTagB"] != "second": is_success = False print("Error: Incorrect native call for threading timer") wrap_teapot = local_env["wrapObj"] if (local_env["nativeCallWithWrapperObjTagA"] != 10 or wrap_teapot is None or wrap_teapot.Name != local_env["nativeCallWithWrapperObjName"]): is_success = False print("Error: Incorrect native call with wrapper object for threading timer") return is_success
def lower_note(note, num_semitones): """ Lowers the note passed in by the number of semitones in num_semitones. :param note: string: The note to be lowered :param num_semitones: The number of times the note passed in is to be lowered :return: string: A note one or more semitones lower than the one passed in """ # start with the note passed in lowered_note = note for i in range(num_semitones): # if the note involves '+' then all we need to do is trim the last character from the string if '+' in lowered_note: lowered_note = lowered_note[:-1] # if the note does not involve '+' then all we need to do is append '-' to the end of the string else: as_list = list(lowered_note) as_list.append('-') lowered_note = ''.join(as_list) return lowered_note
def flatten(l): """ Flatten a list into a 1D list """ return [item for sublist in l for item in sublist]
def ACC_calc(TP, TN, FP, FN): """ Calculate accuracy. :param TP: true positive :type TP : int :param TN: true negative :type TN : int :param FP: false positive :type FP : int :param FN: false negative :type FN : int :return: accuracy as float """ try: result = (TP + TN) / (TP + TN + FN + FP) return result except ZeroDivisionError: return "None"
def is_number(s): """ Returns True is string is a number. """ try: float(s) return True except ValueError: return False
def zeros_matrix(rows, cols): """ Creates a matrix filled with zeros. :param rows: the number of rows the matrix should have :param cols: the number of columns the matrix should have :return: list of lists that form the matrix """ M = [] while len(M) < rows: M.append([]) while len(M[-1]) < cols: M[-1].append(0.0) return M
def remove_duplicates(seq): """Remove duplicates from a sequence preserving order. Returns ------- list Return a list without duplicate entries. """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
def via_point_generate(path): """ path to linear via point generator (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13) | | V | (2, 4) , (2, 13) <---------------------------------------------------------- origin destination """ vp = list(path) i = 0 while i < len(vp): if i + 1 < len(vp): if (vp[i][0] - vp[i + 1][0] == 0 and vp[i][0] - vp[i - 1][0] == 0)or \ (vp[i][1] - vp[i + 1][1] == 0 and vp[i][1] - vp[i - 1][1] == 0): vp.remove(vp[i]) # if i != len(vp) - 2: i -= 1 i += 1 return vp
def is_palindrome(phrase): """Is phrase a palindrome? Return True/False if phrase is a palindrome (same read backwards and forwards). >>> is_palindrome('tacocat') True >>> is_palindrome('noon') True >>> is_palindrome('robert') False Should ignore capitalization/spaces when deciding: >>> is_palindrome('taco cat') True >>> is_palindrome('Noon') True """ s = phrase.lower().translate(str.maketrans('', '', ' \n\t\r')) r = s[::-1] return r == s
def ip_inputfiles(filenames, ipname): """Create input files per IP""" inputfiles = [None, "tmp.raw", "tmp.ui", "tmp.all"] num_infiles = 1 if ipname in ["pse", "fkm", "tccp"]: inputfiles.extend(["tmp.cmps", "tmp.guid"]) elif ipname in ["gop", "gfxpeim", "undi"]: inputfiles.remove("tmp.raw") inputfiles.insert(1, "tmp.pe32") if ipname == "gfxpeim": inputfiles.append("tmp.cmps") # add user given input files infiles = filenames[1:num_infiles + 1] inputfiles[1:1] = infiles return inputfiles, num_infiles
def generate_res(body): """Wraps `body` in XML parent tags to mirror API response.""" return f'<?xml version="1.0" encoding="utf-8"?><MRData total="1">{body}</MRData>'
def normalize_hex(hex_color): """Transform a xxx hex color to xxxxxx.""" hex_color = hex_color.replace("#", "").lower() length = len(hex_color) if length in (6, 8): return "#" + hex_color if length not in (3, 4): return None strhex = u"#%s%s%s" % (hex_color[0] * 2, hex_color[1] * 2, hex_color[2] * 2) if length == 4: strhex += hex_color[3] * 2 return strhex
def clean_line(line): """ Removes existing <br> line breaks from the file so they don't multiply. """ return line.replace("<br>", "")
def build_path_split(path): """Return list of components in a build path""" return path.split('/')
def build_varint(val): """Build a protobuf varint for the given value""" data = [] while val > 127: data.append((val & 127) | 128) val >>= 7 data.append(val) return bytes(data)
def polar_partition(value, front_back): """ asymmetric partitioning of inclusion body """ # front aggregate goes to the front daughter if 'front' in front_back: aggregate = front_back['front'] return [aggregate, 0.0] # back aggregate goes to the back daughter elif 'back' in front_back: aggregate = front_back['back'] return [0.0, aggregate]
def _is_dependent_on_sourcekey(sourcekey, source_def): """Tests if 'source_def' is dependent on 'sourcekey'. """ # case: source_def is not a pseudo-column if not isinstance(source_def, dict): return False # case: sourcekey referenced directly if sourcekey == source_def.get('sourcekey'): return True # case: sourcekey in path prefix if not isinstance(source_def.get('source'), str) and sourcekey == source_def.get('source', [{}])[0].get('sourcekey'): return True # case: sourcekey in wait_for if sourcekey in source_def.get('display', {}).get('wait_for', []): return True # not dependent return False
def format_size(size): """ :param float size: :rtype: str """ size = float(size) unit = 'TB' for current_unit in ['bytes', 'KB', 'MB', 'GB']: if size < 1024: unit = current_unit break size /= 1024 return '{0:.2f}'.format(size).rstrip('0').rstrip('.') + ' ' + unit
def safe_max(*args, **kwargs): """ Regular max won't compare dates with NoneType and raises exception for no args """ non_nones = [v for v in args if v is not None] if len(non_nones) == 0: return None elif len(non_nones) == 1: return non_nones[0] else: return max(*non_nones, **kwargs)
def _python2_load_cpkl(fpath): """ References: https://stackoverflow.com/questions/41720952/unpickle-sklearn-tree-descisiontreeregressor-in-python-2-from-python3 """ from lib2to3.fixes.fix_imports import MAPPING import sys import pickle # MAPPING maps Python 2 names to Python 3 names. We want this in reverse. REVERSE_MAPPING = {} for key, val in MAPPING.items(): REVERSE_MAPPING[val] = key # We can override the Unpickler and loads class Python_3_Unpickler(pickle.Unpickler): """Class for pickling objects from Python 3""" def find_class(self, module, name): if module in REVERSE_MAPPING: module = REVERSE_MAPPING[module] __import__(module) mod = sys.modules[module] klass = getattr(mod, name) return klass def load(fpath): with open(fpath, 'rb') as file_: data = Python_3_Unpickler(file_).load() return data
def get_texts(num): """get sample texts Args: num(int): number of texts to return Returns: list: list of sample texts """ return ["SAMPLE" for i in range(num)]
def get_word_reverse(text): """ >>> get_word_reverse('This is for unit testing') 'sihT si rof tinu gnitset' """ words = text.split() return ' '.join([word[::-1] for word in words])
def change_polarity(mutation): """ Return + if the protein mutation introduce a change in the polarity of the residue. """ groups = { "Ala": "Non polar", "Asn": "Polar", "Asp": "Acidic", "Arg": "Basic", "His": "Basic", "Cys": "Cysteine", "Gln": "Polar", "Glu": "Acidic", "Gly": "Glicine", "Pro": "Proline", "Leu": "Non polar", "Lys": "Basic", "Ile": "Non polar", "Met": "Non polar", "Phe": "Non polar", "Ser": "Polar", "Thr": "Polar", "Tyr": "Polar", "Trp": "Non polar", "Val": "Non polar", } if "Ter" in mutation: return "-" if "*" in mutation: return "-" if "?" in mutation: return "-" polarity_wt = groups[mutation[2:5]] polarity_mutant = groups[mutation[-3:]] if polarity_wt != polarity_mutant: return '+' else: return '-'
def calculate_expected_duration(optimistic, nominal, pessimistic): """ Calculate the expected duration of a task. """ return round((optimistic + (4 * nominal) + pessimistic) / 6, 1)
def compute_alphabet(sequences): """ Returns the alphabet used in a set of sequences. """ alphabet = set() for s in sequences: alphabet = alphabet.union(set(s)) return alphabet
def es_vocal(letra): """ Valida si una letra es vocal >>> es_vocal('a') True >>> es_vocal('b') False >>> es_vocal('ae') Traceback (most recent call last): .. ValueError: ae no es una letra >>> es_vocal('1') Traceback (most recent call last): .. ValueError: 1 no es una letra :param letra: :return: """ if (len(letra) == 1 and letra.isalpha()): return letra in 'aeiouAEIOU' raise ValueError(letra + ' no es una letra')
def calc_row_checksum(row_data): """ Method for calculating the checksum for a row. """ min_val = 0 max_val = 0 first = True for cell in row_data.split("\t"): if first: min_val = int(cell) max_val = int(cell) first = False else: if min_val > int(cell): min_val = int(cell) if max_val < int(cell): max_val = int(cell) return max_val - min_val
def fix_label_lists(tsv_file_lst_lsts): """ complex and anchor_files have first element of complex labels for an ID this list is imported as one string and needs to be list of integers, which is done in this function output is dict with ID as key and labels as value labels are ints """ comp_dict = {} for ele in tsv_file_lst_lsts: comp_dict[ele[1]] = [int(i) for i in ele[0].split(',') ] return comp_dict
def pluralize(word, override): """Helper to get word in plural form.""" if word in override: return override[word] return word + 'es' if word[-1] == 's' else word + 's'
def nl(x, gamma): """ Nonlinearity of the form .. math:: f_{\\gamma}(x) = \\frac{1}{1-\\gamma x} Args: x (:class:`numpy.array`): signal gamma (float): Nonlinearity parameter Note: The integral of ``gamma * nl(x, gamma)`` is .. math:: \\int \\frac{\\gamma}{1 - \\gamma x} = -\\log (1 - \\gamma x) """ return 1.0/(1.0-gamma*x)
def pitch_to_str(pitch): """ Calculate the corresponding string representation of a note, given the MIDI pitch number Args: pitch (int): MIDI pitch number Returns: str: corresponding note name """ p_to_l_dic = {0: 'C', 1: 'C#', 2: 'D', 3: 'D#', 4: 'E', 5: 'F', 6: 'F#', 7: 'G', 8: 'G#', 9: 'A', 10: 'A#', 11: 'B'} return p_to_l_dic[pitch % 12]
def subsets(l,ln, partial=[]): """ Generates the subsets of l that have ln elements. """ if len(partial) == ln: return [partial] results = [] for x in l: if not partial or x >= partial[-1]: nextp = partial[:] nextp.append(x) nextl = l[:] nextl.remove(x) results.extend(subsets(nextl,ln,nextp)) return results
def format_date(date: str): """ This function formats dates that are in MM-DD-YYYY format, and will convert to YYYY-MM-DD, which is required sqlite. :param date: The date to modify. :return: The modified string. """ tmp = date.split("/") return "{}-{}-{}".format(tmp[2], tmp[0], tmp[1])
def length(*t, degree=2): """Computes the length of the vector given as parameter. By default, it computes the Euclidean distance (degree==2)""" s=0 for x in t: s += abs(x)**degree return s**(1/degree)
def is_object(value): """Checks if `value` is a ``list`` or ``dict``. Args: value (mixed): Value to check. Returns: bool: Whether `value` is ``list`` or ``dict``. Example: >>> is_object([]) True >>> is_object({}) True >>> is_object(()) False >>> is_object(1) False .. versionadded:: 1.0.0 """ return isinstance(value, (list, dict))
def lmap(f, xs): """A non-lazy version of map.""" return list(map(f, xs))