content
stringlengths
42
6.51k
def power_digit_sum(n): """Given integer n, return the sum of digits in 2**n""" i = 2 << (n-1) s = str(i) my_sum = 0 for c in s: my_sum += int(c) return my_sum
def vmul_scalar(vector, scalar): """ mul vector with scalar """ return (vector[0]*scalar, vector[1]*scalar)
def first(list: list, value, comp): """ Index of first element that satisfies 'element comp value' relation :param list: :param value: :param comp: :return: """ if comp == 'gt': return next(x[0] for x in enumerate(list) if x[1] > value) elif comp == 'ge': return next(x[0] for x in enumerate(list) if x[1] >= value) elif comp == 'lt': return next(x[0] for x in enumerate(list) if x[1] < value) elif comp == 'le': return next(x[0] for x in enumerate(list) if x[1] <= value)
def log_message(source, *parts): """Build log message.""" message = source.__class__.__name__ for part in parts: message += f": {part!s}" return message
def processed_events(object_type: str, subscriber: str) -> str: """Return the db key used to store processed events. This is the key where processed events for the specified subscriber and object type are stored. Args: object_type (str): Type of object subscriber (str): Subscriber name Returns: str, db key where processed events are stored. """ return 'events:{}:{}:processed'.format(object_type, subscriber)
def _to_text(nodes_or_text): """Convert a xpath object (a string or a list of nodes) to string""" element0 = (nodes_or_text[0] if isinstance(nodes_or_text, list) else nodes_or_text) return (element0 if isinstance(element0, str) else element0.xpath("string(.)"))
def elo_simple(homeElo, awayElo, goalDiff, k, debug=False): """ Elo ranking system based only on wins. No Homefield Advantage. No Goal Diferential. No season regression. Parameters ---------- homeElo : float Elo Rating of home team. awayElo : float Elo Rating of away team. goalDiff : Int Goal difference of game (Home - Away) k : Int Elo k-factor. Returns ------- homeElo_adj : float Adjustment to home team's elo awayElo_adj : float Adjustment to away team's elo predictError : float Prediction error as a Brier score for event """ if debug: print('elo_simple in debug mode') # Determine winner of game if goalDiff > 0: result = 1 elif goalDiff < 0: result = 0 else: result = 0.5 # Calutlate expected match score Qa = pow(10, homeElo / 400) Qb = pow(10, awayElo / 400) Ea = Qa / (Qa + Qb) Eb = Qb / (Qa + Qb) # Change in Elo ratings deltaElo = round(k * (result - Ea), 2) # Expected match score error predictError = (result - Ea) ** 2 # Adjust Elo ratings of each team based on result homeElo_adj = round(homeElo + deltaElo, 2) awayElo_adj = round(awayElo - deltaElo, 2) if debug: print('Qa: ', Qa, ' Qb: ', Qb, ' Ea: ', Ea, ' Eb: ', Eb, ' homeElo_adj: ', homeElo_adj, ' awayElo_adj: ', awayElo_adj) return (homeElo_adj, awayElo_adj, predictError)
def grayscale_filename(file_name, index): """ Setting the name of each grayscale file for the i-th frame where i == index :param file_name: :param index: :return: """ split_file = file_name.split('.mp4')[0] return split_file + '_gray_{}.png'.format(index)
def complete_yaml(self, text, line, start_index, end_index): """ This method uses ``inlist`` variable to enable ``cmd`` module command autocompletion """ inlist = ['run'] if text: return [item for item in inlist if item.startswith(text)] else: return inlist
def group(iterable, n_groups): """Group a list into a list of lists This function can be used to split up a big list items into a set to be processed by each worker in an MPI scheme. Parameters ---------- iterable : array_like A list of elements n_groups : int The number of groups you'd like to make Returns ------- groups : list A list of lists, where each element in `groups` is a list of approximately `len(iterable) / n_groups` elements from `iterable` See Also -------- interweave : inverse of this operation """ return [iterable[i::n_groups] for i in range(n_groups)]
def determine_status(resp: dict) -> str: """ Determines the status (`Full`, `Blocked`, `Partial Block` or `Empty`) of or a given keyword's API response (`resp`). Examples for each kind of response in `../data/reference/placements_api_response_examples`. Please read the methodology for more detail. """ if resp['is_blocked'] == True: return 'Blocked' elif resp['n_youtube_channels'] == 0 and resp['n_youtube_videos'] == 0: return 'Empty' elif resp['n_youtube_videos'] == 1: return 'Partial Block' return 'Full'
def split_by_last_word(string_list): """ split list of strings list by last word Args: string_list: list(str), list of text in form of str Returns: list,list the list of text with last word removed and the last word text list """ # return [ ' '.join(s.split()[:-1]) for s in string_list],[ s.split()[-1:][0] for s in string_list] return [ ' '.join(s.split()[:-1]) for s in string_list]
def total(n): """ Returns the sum of the numbers from 0 to n (inclusive). If n is negative, returns None. """ if n < 0: return None else: result = 0 for i in range(n + 1): result += i return result
def get_material_index(glTF, name): """ Return the material index in the glTF array. """ if name is None: return -1 if glTF.get('materials') is None: return -1 index = 0 for material in glTF['materials']: if material['name'] == name: return index index += 1 return -1
def int_to_roman(num: int) -> str: """ Returns an integer number in roman format. ***Parameters*** - `num`: int Input integer. ***Returns*** - `out`: str Roman number for the input. """ val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] syb = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] roman_num = '' i = 0 while num > 0: for _ in range(num // val[i]): roman_num += syb[i] num -= val[i] i += 1 return roman_num
def u(z,t=-2): """ utility of the consumer Args: z (float): random level of good t (float): random parameter Returns: (float): unitily of the consumer """ return z**(1+t)/(1+t)
def divide(a: int, b: int = 1) -> int: """Simple division function for testing run_hook Args: a (int): Dividend b (int, optional): Divisor. Defaults to 1. Returns: int: Quotient """ return int(a/b)
def get_standard(obj, standard): """ A function that allows to return a standard value for an object, if the object is None. :param obj: Object to check if it's None. :param standard: Standard value for the object :return: return the object or the standard value """ if obj is None: return standard return obj
def on_off(true_false): """ Initial Settings :param true_false: :return: (on, off) """ if true_false: return 0, 28 else: return 28, 0
def is_dict_specifier(value): """ Check if a parameter of the task decorator is a dictionary that specifies at least Type (and therefore can include things like Prefix, see binary decorator test for some examples). :param value: Decorator value to check :return: True if value is a dictionary that specifies at least the Type of the key """ return isinstance(value, dict)
def Get_list_date(ddeb,dfin,dlist): """ Retourne les dates d'une liste comprises entre deux dates """ lOutput = list() for x in dlist: if x >= ddeb and x <= dfin: lOutput.append(x) return lOutput
def binomial(n,k): """Compute n factorial by a direct multiplicative method.""" if k > n-k: k = n-k # Use symmetry of Pascal's triangle accum = 1 for i in range(1,k+1): accum *= (n - (k - i)) accum /= i return accum
def extend(*dicts): """Create a new dictionary from multiple existing dictionaries without overwriting.""" new_dict = {} for each in dicts: new_dict.update(each) return new_dict
def _pval_to_opacity_worker(pval: float, alpha: float = 0.05, nonsig_max: float = 0.25) -> float: """ Converts p-values or fdr to opacity, with opacity cliff at `alpha` where opacity is 1 below `alpha`, and linearly interpolated between `nonsig_max` and 0 from `alpha` to 1. Args: pval: p-value or fdr to convert to opacity alpha: significance threshold for opacity cliff nonsig_max: maximum opacity for non-significant results Returns: """ if pval < alpha: return 1 else: return nonsig_max * (1 - pval)
def schemaMatch(schema,object): """Returns true if the object matches the given schema.""" if schema is None: return True if isinstance(schema,(list,tuple)): if not isinstance(object,(list,tuple)): return False if len(schema) != len(schema): return False for (a,b) in zip(schema,object): if not schemaMatch(a,b): return False return True elif isinstance(schema,dict): if not isinstance(schema,dict): return False if len(schema) != len(object): return False for k,v in schema.items(): try: v2 = object[k] except KeyError: return False if not schemaMatch(v,v2): return False return True elif hasattr(schema, '__call__'): #predicate return schema(object) else: return (schema==object)
def length(head) -> int: """ The method length, which accepts a linked list (head), and returns the length of the list. :param head: :return: """ i = 0 if head is None: return 0 while head.next is not None: head = head.next i += 1 return i + 1
def get_period_index_from_imt_str(imtstr, imt_per_ix): """ Get the index for the period of the specified IMT. Args: imtstr (str): The (OQ-style) IMT string. imt_per_ix (dict): Dictionary relating periods to their indices. Returns: int: The index corresponding to the period of the IMT. """ if imtstr == 'PGA': return imt_per_ix['0.01'] elif imtstr in ('PGV', 'MMI'): return imt_per_ix['1.0'] else: return imt_per_ix[imtstr.replace('SA(', '').replace(')', '')]
def update_dic_keys(d:dict, **kwargs) -> dict: """ Utility to update a dictionary, with only updating singular parameters in sub-dictionaries. Used when updating and configuring/templating job configs. Parameters ---------- d : dict Dictioanry to update **kwargs : dict, optional All extra keyword arguments will be interpreted as items to override in d. Returns ------- err_code : int An SFTP error code int like SFTP_OK (0). """ # Treat kwargs as override parameters for key, value in kwargs.items(): old_val = d.get(key) if type(old_val) is dict: d[key].update(value) else: d[key] = value return d
def _create_graph_from_edges(edges): """Creates a dependency graph from the passed in edges. :param list edges: A list of pairs from parent to child dependencies. :return: The edges as a dependency graph. :rtype: dict. """ g = {} for n1, n2 in edges: n1 = n1.strip() n2 = n2.strip() if n1 not in g: g[n1] = [] if n2 not in g: g[n2] = [] g[n1].append(n2) return g
def indices(s,v): """return in indices of s that have value v""" L = [] for i in range(len(s)): if s[i]== v: L = L+[i] return L
def calc_bar(value, *args): """Calculate percentage of value out of the maximum of several values, for making a bar chart.""" top = max(args + (value,)) percent = value / top * 100 return percent
def to_dict(**kwargs): """Create a dictionary from keyword arguments""" dict = locals() return dict['kwargs']
def kelvtoreau(kelvin): """ This function converts kelvin to Reaumur, with kelvin as parameter.""" Reaumur = (kelvin - 273.15) * 0.8 return Reaumur
def isValidSubsequence_for(array, sequence): """ to find second array is subsequence of the first. One has to iterate through the first array. By which mean time complexity of the problem is going to be O(n) where n is the lenght of the array. During iteration, if the first element in the sequence matches the order in the array only then seq_index is incremented and the process continues. """ seq_index = 0 for value in array: if value == sequence[seq_index]: seq_index+=1 if seq_index == len(sequence): break return seq_index == len(sequence)
def metadata_item_format(value): """Space-separated values in 'key=value' format.""" try: data_name, data_value = value.split('=') except ValueError: message = ("Incorrectly formatted metadata. " "Argument values should be in the format a=b c=d") raise ValueError(message) return {'name': data_name, 'value': data_value}
def median(xs): """Return the median of some numeric values. Assumes that the input list is sorted. """ mid = len(xs) // 2 if len(xs) % 2 == 0: return (xs[mid] + xs[mid - 1]) / 2 else: return xs[mid]
def inject_get_param(request, injectionstring): """ Generates a list of new requests with replaced/modified POST values :param request: request instance :param injection_string: list of strings to inject into the request :return: list of requests """ requests = [] return requests
def gather_deps(files, rawdeps): """ Aggregate the dependency information collected by importlint() and optionally print it out in Make format """ def visit_scc(cn): "Helper function for strongly connected component search" # We use the length of lowlinks instead of a global counter because # of the scoping rules of Python 2 (which we want to remain compatible # to). indices[cn] = len(lowlinks) lowlinks[cn] = len(lowlinks) stack.append(cn) stackset.add(cn) # Now, look through the 'successors' of cn. for d in deps.get(cn, ()): if d not in indices: visit_scc(d) lowlinks[cn] = min(lowlinks[cn], lowlinks[d]) elif d in stackset: lowlinks[cn] = min(lowlinks[cn], indices[d]) # If the current node does not refer to a predecessor on the stack, # we have finished traversing a strongly connected component and can # recover it from the stack. if lowlinks[cn] == indices[cn]: scc = set() scc_groups[cn] = scc while 1: d = stack.pop() stackset.remove(d) scc.add(d) rev_scc_groups[d] = cn if d == cn: break def visit_fd(rcn): "Helper function for transitive dependency enumeration" if rcn in fulldeps: return fdl = set(scc_groups[rcn]) for rd in scc_deps[rcn]: if rd == rcn: continue visit_fd(rd) fdl.update(fulldeps[rd]) for cn in scc_groups[rcn]: fulldeps[cn] = fdl # Filter out bogus dependencies. deps = {} for cn, dl in rawdeps.items(): deps[cn] = set(d for d in dl if d in files) deps[cn].add(cn) # We use Tarjan's pertinent algorithm to locate the strongly connected # components of the dependency graph; every node in a strongly connected # component has (because of the strong connectedness) the same set of # dependencies. indices, lowlinks, stack, stackset = {}, {}, [], set() scc_groups, rev_scc_groups = {}, {} for cn in deps: if cn not in indices: visit_scc(cn) # We contract the SCCs to single representative vertices to simplify the # next step. scc_deps = {} for cn, dl in deps.items(): scc_deps.setdefault(rev_scc_groups[cn], set()).update( rev_scc_groups[d] for d in deps[cn]) # Finally, we can traverse the resulting (acyclic) graph to collect the # transitive dependencies of every node. fulldeps = {} for rcn in scc_deps: visit_fd(rcn) # Map the class names to file names. filedeps = {} for cn, dl in fulldeps.items(): filedeps[files[cn]] = set(files[d] for d in dl) # Done. return filedeps
def jinja_hasattr(obj, string): """Template filter checking if the provided object at the provided string as attribute """ return hasattr(obj, string)
def dist(v1, v2, res): """ Contributions ------------- Author: Editor: """ return ((res[0] * (v1[0] - v2[0])) ** 2 + (res[1] * (v1[1] - v2[1])) ** 2 + (res[2] * (v1[2] - v2[2])) ** 2) ** 0.5
def recursive_sum(arr): """Return the sum of a 2D array.""" if len(arr) == 0: return 0 else: return arr[0] + recursive_sum(arr[1:])
def tabFibo(n): """ Fibonacci numbers solved with tabulation """ base = [1, 1] for i in range(2, n + 1): base.append(base[i - 1] + base[i - 2]) return base[n]
def _and(*args): """Helper function to return its parameters and-ed together and bracketed, ready for a SQL statement. eg, _and("x=1", "y=2") => "(x=1 AND y=2)" """ return " AND ".join(args)
def escape_for_bash(str_to_escape): """ This function takes any string and escapes it in a way that bash will interpret it as a single string. Explanation: At the end, in the return statement, the string is put within single quotes. Therefore, the only thing that I have to escape in bash is the single quote character. To do this, I substitute every single quote ' with '"'"' which means: First single quote: exit from the enclosing single quotes Second, third and fourth character: "'" is a single quote character, escaped by double quotes Last single quote: reopen the single quote to continue the string Finally, note that for python I have to enclose the string '"'"' within triple quotes to make it work, getting finally: the complicated string found below. """ escaped_quotes = str_to_escape.replace("'", """'"'"'""") return "'{}'".format(escaped_quotes)
def treasury_bill_price(discount_yield, days_to_maturity): """Computes price ot treasury bill""" return 100 * (1 - days_to_maturity / 360 * discount_yield)
def escape(value, char, escape = "\\"): """ Escapes the provided string value according to the requested target character and escape value. Meaning that all the characters are going to be replaced by the escape plus character sequence. :type value: String :param value: The string that is going to have the target characters escaped according to the escape character. :type char: String :param char: The character that is going to be "target" of escaping. :type escape: String :param escape: The character to be used for escaping (normally`\`). :rtype: String :return: The final string with the target character properly escaped. """ return value.replace(escape, escape + escape).replace(char, escape + char)
def seconds(ts, epoch_offset_sec=631152000) -> float: """ Converts LCLS2 timestamp to unix epoch time. The epoch used is 1-Jan-1990 rather than 1970. -Matt Receives ts = orun.timestamp # 4193682596073796843 relative to 1990-01-01 Returns unix epoch time in sec # 1607569818.532117 sec import datetime epoch_offset_sec=(datetime.datetime(1990, 1, 1)-datetime.datetime(1970, 1, 1)) / datetime.timedelta(seconds=1) """ return float(ts>>32) + float(ts&0xffffffff)*1.e-9 + epoch_offset_sec
def average(dictionary, key): """ Get average value from a dictionary in a template @param dictionary: dictionary @param key: what key to look for @return: value """ total = 0 for item in dictionary: total += item[key] return total / len(dictionary)
def _make_state_lock_key(game_id: str) -> str: """Make the redis key for locking the game state.""" return 'ttt:{}.state_lock'.format(game_id)
def hamming_distance(s1, s2): """ Get Hamming distance: the number of corresponding symbols that differs in given strings. """ return sum(i != j for i, j in zip(s1, s2))
def line_length_check(line): """Return TRUE if the line length is too long""" if len(line) > 79: return True return False
def get_translation_count1(num: int) -> int: """ Parameters ----------- Returns --------- Notes ------ """ if num < 0: return 0 s = str(num) lenth = len(s) counts = [0] * lenth + [1] for i in reversed(range(lenth)): count = counts[i+1] if i < lenth - 1: digit1 = int(s[i]) digit2 = int(s[i+1]) converted = digit1 * 10 + digit2 if 10 <= converted <= 25: count += counts[i+2] counts[i] = count print(counts) return counts[0]
def cleanPath(path): """ Cleans up raw path of pdf to just the name of the PDF (no extension or directories) :path: path to pdf :returns: The PDF name with all directory/extensions stripped """ filename = path.split("/")[-1] filename = filename.split(".")[0] return filename
def get_current_top_category(request, obj): """ Returns the current top category of a product. """ if obj.__class__.__name__.lower() == "product": category = obj.get_current_category(request) else: category = obj if category is None: return category while category.parent is not None: category = category.parent return category
def isadjacentdiagonal(a, b): """Returns true if a is adjacent to be(with diagonal), if they are not adjacent returns false""" ax = a['x'] ay = a['y'] bx = b['x'] by = b['y'] xdiff = ax - bx ydiff = ay - by if xdiff in range(-1, 2) and ydiff in range(-1, 2): return True else: return False
def coord2mssroi(coord, cropRegion=False, topCrop=0, bottomCrop=0, leftCrop=0, rightCrop=0): """Transforms coordinates to MSS ROI format""" roi = {'top': coord[0][1], 'left': coord[0][0], 'width': coord[1][0]-coord[0][0], 'height': coord[1][1]-coord[0][1]} if cropRegion: roi['top'] = roi['top'] + topCrop * roi['height'] roi['left'] = roi['left'] + leftCrop * roi['width'] roi['width'] = roi['width'] * ( 1 - ( leftCrop + rightCrop )) roi['height'] = roi['height'] * (1 - (topCrop + bottomCrop)) return roi
def _obj_to_dict(obj): """Convert an object into a hash for debug.""" return {key: getattr(obj, key) for key in dir(obj) if key[0] != '_' and not hasattr(getattr(obj, key), '__call__')}
def addExtraPermInfo(perms): """ Apply some cleanups/simplifications for more digestable permission indicators by clients. - We only include one of moderator/admin (admin if both, moderator if mod but not admin) - Don't include moderator/admin at all when both are false - We rewrite visible_mod=False to hidden=True (and omit both if not a mod/admin, or not hidden) - Don't include banned unless true. """ vis_mod = perms.pop("visible_mod", True) if perms["moderator"]: if not vis_mod: perms["hidden"] = True del perms["moderator" if perms["admin"] else "admin"] else: del perms["moderator"] del perms["admin"] if not perms["banned"]: del perms["banned"] return perms
def get_atoms(target): """Use individual tokens as atoms.""" atoms = set() for token in target.split(): if token not in ("(", ")", ","): atoms.add(token) return atoms
def _get_dimension(region): """ Return dimensionality of `region` (0, 1, 2, or 3). """ if len(region) == 7: zone_name, imin, imax, jmin, jmax, kmin, kmax = region elif len(region) == 5: zone_name, imin, imax, jmin, jmax = region kmin, kmax = 0, 0 else: zone_name, imin, imax = region jmin, jmax, kmin, kmax = 0, 0, 0, 0 dim = 0 if imin != imax: dim += 1 if jmin != jmax: dim += 1 if kmin != kmax: dim += 1 return dim
def get_file_name(x): """ Create a file name with today's date" """ return "./graph-"+x
def replace__from__by__from_(d: dict): """Replace recursive keys in the object from to from_.""" res = {} if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [replace__from__by__from_(v) for v in d] for key, value in d.items(): if key == 'from': res['from_'] = replace__from__by__from_(d['from']) else: res[key] = replace__from__by__from_(d[key]) return res
def round_and_clip_image(image): """ Given a dictionary, ensure that the values in the 'pixels' list are all integers in the range [0, 255]. All values should be converted to integers using Python's `round` function. Any locations with values higher than 255 in the input should have value 255 in the output; and any locations with values lower than 0 in the input should have value 0 in the output. """ result = image.copy() s = len(result['pixels']) for i in range(s): x = round(result['pixels'][i]) if x < 0: x = 0 elif x > 255: x = 255 result['pixels'][i] = x return result
def get_license(j): """ By default, the license info can be achieved from json["info"]["license"] In rare cases it doesn't work. We fall back to json["info"]["classifiers"], it looks like License :: OSI Approved :: BSD Clause """ if j["info"]["license"] != "": return j["info"]["license"] for k in j["info"]["classifiers"]: if k.startswith("License"): ks = k.split("::") return ks[2].strip() return ""
def header_column_rename(header_list: list, column_name: str, column_index: int): """Rename column with a name Args: header_list (list, required): header list param to convert the month. column_name (str, required): New name for the column column_index (int, required): index of the column Returns: pandas.DataFrame: header list """ header_list[column_index] = column_name return header_list
def PaethPredictor(a: int, b: int, c: int) -> int: # pragma: no cover """ See: http://www.libpng.org/pub/png/spec/1.2/PNG-Filters.html "A simple predictive-corrective coding filter" or P-C filter, described in Paeth (1991) "Image File Compression Made Easy". """ p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: Pr = a elif pb <= pc: Pr = b else: Pr = c return Pr
def split_path(path): """Split a *canonical* `path` into a parent path and a node name. The result is returned as a tuple. The parent path does not include a trailing slash. >>> split_path('/') ('/', '') >>> split_path('/foo/bar') ('/foo', 'bar') """ lastslash = path.rfind('/') ppath = path[:lastslash] name = path[lastslash + 1:] if ppath == '': ppath = '/' return (ppath, name)
def contar_caracteres(s): """Funcao que conta os caracteres de uma string. Ex: >>> contar_caracteres('adao') {'a': 2, 'd': 1, 'o': 1} >>> contar_caracteres('banana') {'a': 3, 'b': 1, 'n': 2} :param s: string a ser contada """ resultado = {} for caracter in s: resultado[caracter] = resultado.get(caracter, 0) + 1 return resultado
def compute_flux_points_ul(quantity, quantity_errp): """Compute UL value for fermi flux points. See https://arxiv.org/pdf/1501.02003.pdf (page 30) """ return 2 * quantity_errp + quantity
def bits_to_byte(bits): """ Return int represented by bits, padded on right. @param str bits: a string representation of some bits @rtype: int >>> bits_to_byte("00000101") 5 >>> bits_to_byte("101") == 0b10100000 True """ return sum([int(bits[pos]) << (7 - pos) for pos in range(len(bits))])
def bold(msg: str) -> str: """Return bold string in rich markup""" return f"[bold]{msg}[/bold]"
def fix_ncesid(ncesid, mode): """ Applies standard formatting (zero padding and typecasting) to both schools' and districts' NCES IDs. Args: ncesid (int): Target NCES ID to fix (e.g. 100005). mode (str): Should be either "school" or "district". Returns: str: Standardized NCES ID (does not perform zero padding if unknown mode is porvided). """ padding = { "school": 12, "district": 7 }.get(mode, 0) return str(ncesid).zfill(padding)
def backcomp(arglist): """Modify arglist for backwards compatibility""" for i in range(len(arglist)): if arglist[i] == "attr": arglist[i] = "write-attr" elif arglist[i] == "--known-endpoints": arglist[i] = "--ep-known" try: arglist.remove("--echo") except ValueError: pass return arglist
def merge_dicts(*dicts): """ Takes N number of dicts and updates them to the left-most dict >>> merge_dicts({}) {} >>> merge_dicts({}, {}) {} >>> merge_dicts({'a': 1}, {'b': 2}) {'a': 1, 'b': 2} >>> merge_dicts({'a': 1}, {}) {'a': 1} >>> merge_dicts({'a': {'a': 1}}, {'a': {'b': 2}}) {'a': {'b': 2}} >>> merge_dicts(None) {} """ def merge(a, b): z = a.copy() z.update(b) return z x = {} for d in dicts: if not d: d = {} x = merge(x, d) return x
def is_private(key): """ Returns whether or not an attribute is private. A private attribute looks like: __private_attribute__. :param key: The attribute key :return: bool """ return key.startswith("__") and key.endswith("__")
def checkIfCoordinateIsInCoordinateSystem(givenX, givenY, coordinateSystem): """ Checks if a specific coordinate is withing the playground/coordinatesystem :param givenX: x coordinate :param givenY: y coordinate :param coordinateSystem: coordinate system to check :return: if coordinate is withing the coordinatesystem """ return ( len(coordinateSystem) > givenY >= 0 and len(coordinateSystem[0]) > givenX >= 0 )
def __abs_nearest_dist(positions, size): """ Absolute nearest distance calculation """ assert(isinstance(positions, list)) if len(positions) == 0: positions.append(0) result = [] for i in range(size): dist = min([abs(i - pos) for pos in positions]) result.append(dist) return result
def split_ep(entry_point): """ Split an entry point string into name, module, target. Parameters ---------- entry_point : EntryPoint Entry point object. Returns ------- tuple (entry_point_name, module_name, target_name). """ epstr = str(entry_point) name, rest = epstr.split('=', 1) name = name.strip() module, target = rest.strip().split(':', 1) return name, module, target
def is_prime(number: int) -> bool: """ Checks if `number` is a prime number. Parameters ---------- number : The number to check for primality. Returns ------- is_number_prime : `bool` Boolean indicating if `number` is prime or not. """ if number <= 1: return False # number ** 0.5 is faster than math.sqrt(number) for x in range(2, int(number**0.5) + 1): # Return False if number is divisible by x if number % x == 0: return False return True
def integer(string): """Takes a string and returns an integer""" s = string.replace('.', '') s = int(s) return s
def _scale_vars(s, v_list): """Scale all variables in v_list by s.""" return [s * v for v in v_list]
def get_most_rare_letter(items=[]): """ :param items: item list to find out the most rarely occurred :return: one object from the item list """ from operator import itemgetter if len(items) == 0: return 'Not existed' else: # get all first letters list first_letters_list = list(map(lambda x: x[0], items)) # get the unique letters set first_letters_set = set(first_letters_list) # counts for each unique letter pairs = list(map(lambda x: (x, first_letters_list.count(x)), first_letters_set)) sorted_pairs = sorted(pairs, key=itemgetter(1), reverse=False) print('General statistics: ', sorted_pairs) pair_min = sorted_pairs[0] return pair_min
def bits_to_char(bit_seq): """ Converts a list of size 8, composed of 0's and 1's, into a character. Obtains the base 10 value represented by the list of 0's and 1's, and finds the corresponding unicode char for that base 10 value. Args: bit_seq: a list of size 8, composed of 0's and 1's Returns: A character, whose unicode value is equal to the binary value encoded by the list of 0's and 1's """ value = 0 for bit in bit_seq: value = (value * 2) + bit char_val = chr(value) return char_val
def bubblesort(x): """ Describe how you are sorting `x` x will be sorted by comparing the first number to the second and putting them in numerical order next, the second will be compared to the third and the switch repeated (if necessary) The largest numbers will therefore "bubble" up to the end of the vector """ n = len(x) #length of the submitted array for i in range(n): #initialize the for loop for the algorithm so it will run until everything is sorted for j in range(0, n-i-1): #this loop is the function that will actually change the numbers in the array (x) around #The range counts from 0 to length of x minus 1, then once sorted x minus 2, then minus 3.. etc if x[j] > x[j+1]: x[j], x[j+1] = x[j+1], x[j] #IF the number before is greater than the next number, switch their order return x
def sanitize_identifier(identifier): # type: (str) -> str """ Get santized identifier name for identifiers which happen to be python keywords. """ keywords = ( "and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield", ) return "{}_".format(identifier) if identifier in keywords else identifier
def chunk_interslices(nchunks): """Make staggered chunks Similar to chunk_slices, but pick every nth element instead of getting a contiguous patch for each chunk Parameters: nchunks: how many chunks to make Returns: a list of (start, stop, step) tuples with length nchunks Example: >>> chunk_slices(2) == [(0, None, 2), (1, None, 2)] True """ ret = [None] * nchunks for i in range(nchunks): ret[i] = (i, None, nchunks) return ret
def factorial(number): """ Returns True if number is factorial """ product = 1 idx = 1 while product <= number: product = product * idx idx = idx + 1 if product == number: return True return False
def proxyURL(url: str): """Redirects an AIO media link to an https, proxied link to the same file.""" # Proxying is no longer needed as media.focusonthefamily.com supports HTTPS return url.replace('http://', 'https://')
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string int) returns: integer """ # TO DO... <-- Remove this comment when you code this function handLen = 0 for val in hand.values(): handLen = handLen + val return handLen ## return sum(hand.values()) "gives same result"
def mod(x, y, d): """Implement a modify module to provide shortest possible voice leading. """ positive = (x - y) % d negative = (y - x) % d if positive > negative: return -negative return positive
def get_job_name(job: dict) -> str: """Create a job name. Defaults to group name, then rule plus wildcards.""" if job.get("type", "") == "group": groupid = job.get("groupid", "group") jobid = job.get("jobid", "").split("-")[0] jobname = "{groupid}_{jobid}".format(groupid=groupid, jobid=jobid) else: wildcards = job.get("wildcards", {}) wildcards_str = ("_".join(wildcards.values()) or "unique") name = job.get("rule", "") or "rule" jobname = "smk.{0}.{1}".format(name, wildcards_str) return jobname
def clip(num, num_min=None, num_max=None): """Clip to max and/or min values. To not use limit, give argument None Args: num (float): input number num_min (float): minimum value, if less than this return this num Use None to designate no minimum value. num_max (float): maximum value, if more than this return this num Use None to designate no maximum value. Returns float: clipped version of input number """ if num_min is not None and num_max is not None: return min(max(num, num_min), num_max) elif num_min is not None: return max(num, num_min) elif num_max is not None: return min(num, num_max) else: return num
def keywithmaxval(d): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v = list(d.values()) k = list(d.keys()) return k[v.index(max(v))]
def format_correct_answer(category, correct_answer): """ based on the category we may need to format the correct answer so she repeats it back a little slower or spells it out """ # if it's a spelling_backwords question we need # to add spaces into the answer so she spells it out if category == 'spelling_backwords': return correct_answer.replace("", "... ")[1: -1] # if it's repeat add elipses to slow down her saying it back if category == 'repeat': return correct_answer.replace(" ", "... ") return correct_answer
def included(combination, exclude): """ Checks if the combination of options should be included in the Travis testing matrix. """ return not any(excluded in combination for excluded in exclude)
def store_by_gunw(obj_list): """returns a dict where the key is GUNW id and the value is the AOI_TRACK id""" result_dict = {} for obj in obj_list: aoi_track_id = obj.get('_source', {}).get('id', False) gunw_ids = obj.get('_source', {}).get('metadata', {}).get('s1-gunw-ids', []) for gunw_id in gunw_ids: result_dict[gunw_id] = aoi_track_id return result_dict
def flatten_dict(d): """ Flatten dictionary. This code is from: https://stackoverflow.com/questions/52081545/python-3-flattening-nested-dictionaries-and-lists-within-dictionaries """ out = {} for key, val in d.items(): if isinstance(val, dict): val = [val] if isinstance(val, list): for subdict in val: deeper = flatten_dict(subdict).items() out.update({key + '_' + key2: val2 for key2, val2 in deeper}) else: out[key] = val return out
def rectangle_vol(length,width,height): """Usage: rectangle_vol(length rectangle, width of rectangle, height of rectangle)""" return length*width*height
def get_data(key, data, default=list()): """ Safely get the value of a key :param key: key to the data of interest :param data: dictionary holding the data :param default: what to return if the key is missing or empty :return: the value for `key` of default """ if key in data: if data[key] is None: return default else: return data[key] else: return default
def annotate(origin, reference, ops, annotation=None): """ Uses a list of operations to create an annotation for how the operations should be applied, using an origin and a reference target :param origin: The original iterable :type origin: str or list :param reference: The original target :type reference: str or list :ops: The operations to apply :type ops: list of Operation :param annotation: An optional initialization for the annotation. If none is provided, the annotation will be based on the origin. If one is provided, it will be modified by this method. :return: An annotation based on the operations :rtype: list of str """ annotation = annotation or list(origin) for oper in ops: oper.annotate(annotation, origin, reference) for i, label in reversed(list(enumerate(annotation))): if label[0] == '+' and i > 0: annotation[i-1] += label del annotation[i] return annotation