content
stringlengths
42
6.51k
def unique_colors(n_colors): """Returns a unique list of distinguishable colors. These are taken from the default seaborn `colorblind` color palette. Parameters ---------- n_colors The number of colors to return (max=10). """ colors = [ (0.004, 0.451, 0.698), (0.871, 0.561, 0.020), (0.008, 0.620, 0.451), (0.835, 0.369, 0.000), (0.800, 0.471, 0.737), (0.792, 0.569, 0.380), (0.984, 0.686, 0.894), (0.580, 0.580, 0.580), (0.925, 0.882, 0.200), (0.337, 0.706, 0.914), ] assert n_colors <= len(colors) return colors[:n_colors]
def slice_by_limit_and_offset(list, limit, offset): """ Returns the sliced list """ limit = limit + offset if (limit + offset) < len(list) else len(list) return list[offset:limit]
def styblinski_tang(ind): """Styblinski-Tang function defined as: $$ f(x) = 1/2 \sum_{i=1}^{n} x_i^4 - 16 x_i^2 + 5 x_i $$ with a search domain of $-5 < x_i < 5, 1 \leq i \leq n$. """ return sum(((x ** 4.) - 16. * (x ** 2.) + 5. * x for x in ind)) / 2.,
def _pretty_str(value): """ Return a value of width bits as a pretty string. """ if value is None: return 'Undefined' return str(value)
def dprint(d, pre="", skip="_"): """ Pretty print a dictionary, sorted by keys, ignoring private slots (those that start with '_'_). """ def q(z): if isinstance(z, float): return "%5.3f" % z if callable(z): return "f(%s)" % z.__name__ return str(z) lst = sorted([(k, d[k]) for k in d if k[0] != skip]) return pre+'{'+", ".join([('%s=%s' % (k, q(v))) for k, v in lst]) + '}'
def _split_path(path): """split a path return by the api return - the sentinel: - the rest of the path as a list. - the original path stripped of / for normalisation. """ path = path.strip("/") list_path = path.split("/") sentinel = list_path.pop(0) return sentinel, list_path, path
def make_number_formatter(decimal_places): """ Given a number of decimal places creates a formatting string that will display numbers with that precision. """ fraction = '0' * decimal_places return ''.join(['#,##0.', fraction, ';-#,##0.', fraction])
def field(val): """ extract field into result, guess type """ if "," in val: val = map(field, val.split(",")) else: done = False try: val = int(val) done = True except: pass if done: return val try: val = float(val) except: pass return val
def find_bindings(and_measures): """ Find the bindings given the AND measures Parameters ------------- and_measures AND measures Returns ------------- bindings Bindings """ import networkx as nx G = nx.Graph() allocated_nodes = set() for n1 in list(and_measures.keys()): if n1 not in allocated_nodes: allocated_nodes.add(n1) G.add_node(n1) for n2 in list(and_measures[n1].keys()): if n2 not in allocated_nodes: allocated_nodes.add(n2) G.add_node(n1) G.add_edge(n1, n2) ret = list(nx.find_cliques(G)) return ret
def euclidean_dist_vec(y1, x1, y2, x2): """ Vectorized function to calculate the euclidean distance between two points or between vectors of points. Parameters ---------- y1 : float or array of float x1 : float or array of float y2 : float or array of float x2 : float or array of float Returns ------- distance : float or array of float distance or vector of distances from (x1, y1) to (x2, y2) in graph units """ # euclid's formula distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 return distance
def greet(new_name, question): """ greet :param new_name: :param question: :return: """ # return f"Hello, {name}! How's it {question}?" return "Hello, " + new_name + "! How's it " + question + "?"
def get_asset_registry(data): """ Return the asset registry if its available""" if "AssetRegistry" in data and "AssetImportData" in data["AssetRegistry"]: return data["AssetRegistry"]
def get_axis_vector(axis_name, offset=1): """ Returns axis vector from its name :param axis_name: name of the axis ('X', 'Y' or 'Z') :param offset: float, offset to the axis, by default is 1 :return: list (1, 0, 0) = X | (0, 1, 0) = Y | (0, 0, 1) = Z """ if axis_name in ['X', 'x']: return offset, 0, 0 elif axis_name in ['Y', 'y']: return 0, offset, 0 elif axis_name in ['Z', 'z']: return 0, 0, 1
def numeric_target(x): """ Converts distilled list of targets to numerics x: distilled target categories """ numeric_target_dict = { 'none': 0, 'ability': 1, 'age': 2, 'celebrity': 3, 'conservative political figure': 4, 'conservatives': 5, 'ethnicity/immigration status/national origin': 6, 'sex/gender': 7, 'leftists': 8, 'liberal political figure': 9, 'liberals': 10, 'other': 15, 'race': 11, 'religion': 12, 'sexual orientation': 13, 'socioeconomic status': 14 } numeric_targets = [] for annotator in x: numeric_targets_annotator = [] #preserve labels by each annotator for word in annotator: try: numeric_targets_annotator.append(numeric_target_dict[word]) except: for i in word: numeric_targets_annotator.append(numeric_target_dict[i]) numeric_targets.append(numeric_targets_annotator) return numeric_targets
def _init_var_str(name, writer): """Puts a 0 superscript on a string.""" if writer == 'pyxdsm': return '{}^{{(0)}}'.format(name) elif writer == 'xdsmjs': return '{}^(0)'.format(name)
def _decode_ascii(string): """Decodes a string as ascii.""" return string.decode("ascii")
def dictAsKvParray(data, keyName, valueName): """ Transforms the contents of a dictionary into a list of key-value tuples. For the key-value tuples chosen names for the keys and the values will be used. :param data: The dictionary from which the date should be obtained. \t :type data: Dict<mixed, mixed> \n :param keyName: The name assigned to the key of the tuples. \t :type keyName: string \n :param valueName: The name assigned to the value of the tuples \t :type valueName: string \n :returns: A list of key-value tuples with the chosen names for the keys and values. \t :rtype: [{keyName: mixed, valueName: mixed}] \n """ res = [] for key in data.keys(): res.append({keyName: key, valueName: data[key]}) return res
def lowercase_dict(original): """Copies the given dictionary ensuring all keys are lowercase strings. """ copy = {} for key in original: copy[key.lower()] = original[key] return copy
def build_slitw_format_dict(slitw_vals): """Build a dict mapping the slit width vals to matplotlib format statements""" idx = 0 odict = {} slit_fmt_list = ['r.', 'g.', 'b.', 'k.'] n_slit_fmt = len(slit_fmt_list) for slitw in slitw_vals: if slitw not in odict: odict[slitw] = slit_fmt_list[idx % n_slit_fmt] idx += 1 return odict
def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ if len(strs) > 0: common = strs[0] for str in strs[1:]: while not str.startswith(common): common = common[:-1] return common else: return ''
def is_numpy_file(filepath: str) -> bool: """ Helper function to check if the file extension is for npy Parameters --- filepath (str) File path Result --- bool Returns True if file path ends with the npy extension. """ return filepath.endswith(".npy")
def maprange(a, b, s): """ http://rosettacode.org/wiki/Map_range#Python Maps s from tuple range a to range b. """ (a1, a2), (b1, b2) = a, b return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
def stringify_steamids(list_of_steamids): """ Args: list_of_steamids: list of steamids Returns: Single string with steamids separated by comma """ return ','.join(list(map(str, list_of_steamids)))
def best_margin_dict_(regions, r_ids): """ For given list of ids selects region with max margin :param regions: :param r_ids: :return: (margin_value, region_id) """ best_margin = -1 best_margin_id = -1 for r_id in r_ids: if regions[r_id]['margin'] > best_margin: best_margin = regions[r_id]['margin'] best_margin_id = r_id return best_margin, best_margin_id
def domain(fqdn): """Return domain part of FQDN.""" return fqdn.partition('.')[2]
def split_reaches(l, new_reach_pts): """splits l into sections where new_reach_pts contains the starting indices for each slice""" new_reach_pts = sorted(new_reach_pts) sl = [l[i1:i2] for i1, i2 in zip(new_reach_pts, new_reach_pts[1:])] last_index = new_reach_pts[-1] sl.append(l[last_index:]) return sl
def tip_batch(x, n_tip_reuse=1): """Grouping asp/disp into tip-reuse batches """ x = list(x) batchID = 0 channel_cycles = 1 last_value = 0 y = [] for xx in x: if xx < last_value: if channel_cycles % n_tip_reuse == 0: batchID += 1 channel_cycles += 1 y.append(batchID) last_value = xx return y
def combToInt(combination): """Transforms combination from dictionary-list to int-list""" return [item['position'] for item in combination]
def board_to_bitmap(board): """ Returns board converted to bitmap. """ bitmap = bytearray(8) for x, y in board: bitmap[x] |= 0x80 >> y return bitmap
def manipulate_raw_string(raw_string): """ - obtain a list of containers from the initial raw string provided by subprocess """ processed_raw_string = [] for line in str(raw_string).strip().split('\n')[1:]: c_line = line.split() docker_container = [c_line[0], c_line[1], c_line[-1]] processed_raw_string.append(docker_container) return processed_raw_string
def LeftBinarySearch(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ low = 0 high = len(nums) while low < high: mid = (low + high) // 2 if nums[mid] < target: low = mid + 1 else: high = mid assert low == high if low == len(nums) or nums[low] != target: return -1 return low
def to_locale(language): """ Turn a language name (en-us) into a locale name (en_US). Extracted `from Django <https://github.com/django/django/blob/e74b3d724e5ddfef96d1d66bd1c58e7aae26fc85/django/utils/translation/__init__.py#L274-L287>`_. """ language, _, country = language.lower().partition("-") if not country: return language # A language with > 2 characters after the dash only has its first # character after the dash capitalized; e.g. sr-latn becomes sr_Latn. # A language with 2 characters after the dash has both characters # capitalized; e.g. en-us becomes en_US. country, _, tail = country.partition("-") country = country.title() if len(country) > 2 else country.upper() if tail: country += "-" + tail return language + "_" + country
def PemChainForOutput(pem_chain): """Formats a pem chain for output with exactly 1 newline character between each cert. Args: pem_chain: The list of certificate strings to output Returns: The string value of all certificates appended together for output. """ stripped_pem_chain = [cert.strip() for cert in pem_chain] return '\n'.join(stripped_pem_chain)
def _SeparateObsoleteHistogram(histogram_nodes): """Separates a NodeList of histograms into obsolete and non-obsolete. Args: histogram_nodes: A NodeList object containing histogram nodes. Returns: obsolete_nodes: A list of obsolete nodes. non_obsolete_nodes: A list of non-obsolete nodes. """ obsolete_nodes = [] non_obsolete_nodes = [] for histogram in histogram_nodes: obsolete_tag_nodelist = histogram.getElementsByTagName('obsolete') if len(obsolete_tag_nodelist) > 0: obsolete_nodes.append(histogram) else: non_obsolete_nodes.append(histogram) return obsolete_nodes, non_obsolete_nodes
def convert_output(xi, xu): """ Converts the output `xu` to the same type as `xi`. Parameters ---------- xi : int, float or array_like Input to a function which operates on numpy arrays. xu : array_like Output to a function which operates on numpy arrays. Returns ------- xu : int, float or array_like Output in the same type as `xi`. """ if isinstance(xi, float): return float(xu[0]) elif isinstance(xi, int): return int(xu[0]) else: return xu
def _method_prop(obj, attrname, attrprop): """ Returns property of callable object's attribute. """ attr = getattr(obj, attrname, None) if attr and callable(attr): return getattr(attr, attrprop, None)
def get_mdts_for_documents(documents): """Returns list of mdts for provided documents list @param documents: is a set of special CouchDB documents JSON to process""" indexes = {} resp = None if documents: for document in documents: xes = document.mdt_indexes for ind in xes: indexes[ind] = "" resp = indexes.keys() return resp
def extract_file_names(arg, val, args, acc): """ action used to convert string from --files parameter into a list of file name """ acc[arg] = val.split(',') return args, acc
def tl_br_to_plt_plot(t, l, b, r): """ converts two points, top-left and bottom-right into bounding box plot data """ assert t < b and l < r w = r - l; h = b - t X = [l, l, l+w, l+w, l] Y = [t, t+h, t+h, t, t] return X, Y
def obj_to_dict(obj, exclude_params=None): """Non recursively transformer object to dict """ if not exclude_params: exclude_params = [] return dict( (key, obj.__getattribute__(key)) for key in dir(obj) if not callable(obj.__getattribute__(key)) and not key.startswith('_') and key not in exclude_params)
def remove_symbol(text, *symbols): """ Remove entered symbols from text. :param text: Text :param symbols: forbidden symbols. :return: Text without entered symbols. """ entity_prefixes = symbols words = [] for word in text.split(): word = word.strip() if word: if word[0] not in entity_prefixes: words.append(word) return ' '.join(words)
def flatten(list_of_lists): """Flatten a list of lists to a combined list""" return [item for sublist in list_of_lists for item in sublist]
def get_mouths(image): """ Gets bounding box coordinates of all mouths in input image :param image: image :return: list of bounding boxes coordinates, one box for each mouth found in input image """ # spoof implementation return []
def endfInterpolationLine( interpolation ) : """Makes one ENDF interpolation line.""" s = '' for d in interpolation : s += "%11d" % d for i1 in range( len( interpolation ), 6 ) : s += "%11d" % 0 return( s )
def get_key(dict, value): """ Return the first key in the dictionary "dict" that contains the received value "value". Parameters ========== dict: Dict[Any, Any] Dictionary to be used. value: Any Value to be found in the dictionary. """ return list(dict.keys())[list(dict.values()).index(value)]
def cricket_and_football_not_badminton(cricket, badminton, football): """Function which returns the number of students who play both cricket and football but not badminton.""" cricket_and_football = [] # List of students who play cricket and football both req_list_4 = [] # List of students who play cricket and football both but not badminton for i in cricket: for k in football: if i == k: if i not in cricket_and_football: cricket_and_football.append(i) for a in cricket_and_football: for n in badminton: if a not in badminton: if a not in req_list_4: req_list_4.append(a) return len(req_list_4)
def format_results(words, found): """ Format result into strings :param words: :param found: :return: List of strings """ result = [] for word in words: if word in found: (r, c), (x, y) = found[word] result.append("{} ({}, {}) ({}, {})".format(word.upper(), r+1, c+1, x+1, y+1)) else: result.append("{} not found".format(word.upper())) return result
def unflatten(dictionary, sep: str = "."): """Turn a flattened dict into a nested dict. :param dictionary: The dict to unflatten. :param sep: This character represents a nesting level in a flattened key :returns: The nested dict """ nested = {} for k, v in dictionary.items(): keys = k.split(sep) it = nested for key in keys[:-1]: # If key is in `it` we get the value otherwise we get a new dict. # .setdefault will also set the new dict to the value of `it[key]`. # assigning to `it` will move us a step deeper into the nested dict. it = it.setdefault(key, {}) it[keys[-1]] = v return nested
def lambda_handler(event, context): """Sample pure Lambda function Parameters ---------- event: dict, required Choice output { "JobName": "your_job_name", "JobRunId": "jr_uuid", "JobRunState": "SUCCEEDED", "StartedOn": "2021-09-20T20:30:55.389000+00:00", "CompletedOn": "2021-09-20T20:32:51.443000+00:00", "ExecutionTime": 106 } context: object, required Lambda Context runtime methods and attributes Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns ------ Final status of the execution """ output = { "message": "successful glue job execution" } return output
def _mkUniq(collection, candidate, ignorcase = False, postfix = None): """ Repeatedly changes `candidate` so that it is not found in the `collection`. Useful when choosing a unique column name to add to a data frame. """ if ignorcase: col_cmp = [i.lower() for i in collection] can_cmp = candidate.lower() else: col_cmp = collection can_cmp = candidate can_to = "_" + can_cmp if postfix is None else can_cmp + postfix if can_to in col_cmp: res = _mkUniq(col_cmp, can_to, ignorcase, postfix) else: res = can_to return res
def rgb_shade(rbg, percent): """Return shaded rgb by given percent.""" return rbg * (100-percent)/100
def is_numeric_string(txt): """ Checks if a string value can represent an float. Args: txt: A string Returns: A boolean. """ try: float(txt) return True except ValueError: return False
def dotproduct(a, b): """Return a . b Parameters ---------- a : 3-element list of floats first set of values in dot-product calculation b : 3-element list of floats second set of values in dot-product calculation Returns ------- c : 3-element list of floats result of dot-product calculation """ return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]
def rowswap(matlist, index1, index2, K): """ Returns the matrix with index1 row and index2 row swapped """ matlist[index1], matlist[index2] = matlist[index2], matlist[index1] return matlist
def axial_n_moves(f, n, col, slant): """ Return coordinate moved n hexes by the action defined in f. f is expected to be an axial move function. """ for _ in range(n): col, slant = f(col, slant) return col, slant
def ptime(s: float) -> str: """ Pretty print a time in the format H:M:S.ms. Empty leading fields are disgarded with the exception of times under 60 seconds which show 0 minutes. >>> ptime(234.2) '3:54.200' >>> ptime(23275.24) '6:27:55.240' >>> ptime(51) '0:51' >>> ptime(325) '5:25' """ h: float m: float m, s = divmod(s, 60) h, m = divmod(m, 60) ms: int = int(round(s % 1 * 1000)) if not h: if not ms: return "{}:{:02d}".format(int(m), int(s)) return "{}:{:02d}.{:03d}".format(int(m), int(s), ms) if not ms: return "{}:{:02d}:{:02d}".format(int(h), int(m), int(s)) return "{}:{:02d}:{:02d}.{:03d}".format(int(h), int(m), int(s), ms)
def to_str(arg): """ Convert all unicode strings in a structure into 'str' strings. Utility function to make it easier to write tests for both unicode and non-unicode Django. """ if type(arg) == list: return [to_str(el) for el in arg] elif type(arg) == tuple: return tuple([to_str(el) for el in arg]) elif arg is None: return None else: return str(arg)
def get_base_docker_cmd(params): """Parse docker params and build base docker command line list.""" # build command docker_cmd_base = ["docker", "run", "--init", "--rm", "-u", "%s:%s" % (params['uid'], params['gid'])] # add volumes for k, v in params['volumes']: docker_cmd_base.extend(["-v", "%s:%s" % (k, v)]) # set work directory and image docker_cmd_base.extend(["-w", params['working_dir'], params['image_name']]) return docker_cmd_base
def object_name(object): """Convert Python object to string""" if hasattr(object,"__name__"): return object.__name__ else: return repr(object)
def extract_target_size(proc: str): """ Extracts target size as a tuple of 2 integers (width, height) from a string that ends with two integers, in parentheses, separated by a comma. """ a = proc.strip(")").split("(") assert len(a) == 2 b = a[1].split(",") assert len(b) == 2 return (int(b[0]), int(b[1]))
def number_of_bases_above_threshold(high_quality_base_count, base_count_cutoff=2, base_fraction_cutoff=None): """ Finds if a site has at least two bases of high quality, enough that it can be considered fairly safe to say that base is actually there. :param high_quality_base_count: Dictionary of count of HQ bases at a position where key is base and values is the count of that base. :param base_count_cutoff: Number of bases needed to support multiple allele presence. :param base_fraction_cutoff: Fraction of bases needed to support multiple allele presence. :return: True if site has at least base_count_cutoff/base_fraction_cutoff bases, False otherwise (changeable by user) """ # make a dict by dictionary comprehension where values are True or False for each base depending on whether the # count meets the threshold. # Method differs depending on whether absolute or fraction cutoff is specified if base_fraction_cutoff: total_hq_base_count = sum(high_quality_base_count.values()) bases_above_threshold = {base: float(count)/total_hq_base_count >= base_fraction_cutoff and count >= base_count_cutoff for (base, count) in high_quality_base_count.items()} else: bases_above_threshold = {base: count >= base_count_cutoff for (base, count) in high_quality_base_count.items()} # True is equal to 1 so sum of the number of Trues in the bases_above_threshold dict is the number of bases # passing threshold return sum(bases_above_threshold.values())
def get_specific_str(big_str, prefix, suffix): """ Extract a specific length out of a string :param big_str: string to reduce :param prefix: prefix to remove :param suffix: suffix to remove :return: string reduced, return empty string if prefix/suffix not present """ specific_str = big_str if prefix and len(specific_str.split(prefix)) > 1: specific_str = specific_str.split(prefix)[1] if suffix and len(specific_str.split(suffix)) > 1: specific_str = specific_str.split(suffix)[0] if specific_str != big_str: return specific_str else: return ''
def count_possible_decodings(message :str) -> int: """ Get The number of possilbe deconings for a encoded message. The coding mapping is: a : 1, b : 2, ... z : 26 """ if not message: return 1 # get every single position as one possible. num = count_possible_decodings(message[1:]) # the possible 2 char branch adds one possiblility if len(message) >= 2 and int(message[:2]) <= 26: num += count_possible_decodings(message[2:]) return num
def binary_search_recursive(array, start, end, item): """ Recursive version of binary search algorithm Returns index if the item is found in the list, else returns None """ if end >= start: median = (start + end) // 2 if array[median] == item: return median if array[median] < item: return binary_search_recursive(array, median+1, end, item) return binary_search_recursive(array, start, median-1, item) return None
def iso_to_sec(iso): """change a given time from iso format in to seconds""" splited_iso = iso.split(':') return int(float(splited_iso[0]) * 3600 + float(splited_iso[1]) * 60 + float(splited_iso[2]))
def Qdot(q1, q2): """ Qdot """ return q1[0] * q2[0] + q1[1] * q2[1] + q1[2] * q2[2] + q1[3] * q2[3]
def add_points(current_total, points_added, max_possible): """Adds points to a character's score. Args: current_total (int): The current number of points. points_added (int): The points to add. max_possible (int): The maximum points possible for the trait. Return: int: The new number of points. """ if current_total + points_added > max_possible: return max_possible else: return current_total + points_added
def parse_csv_option(option): """Return a list out of the comma-separated option or an empty list.""" if option: return option.split(',') else: return []
def write_dm_id(model_name, dm_id, dm_conj = None): """ Returns entry for DarkMatter_ID in DarkBit. """ towrite = ( "\n" "void DarkMatter_ID_{0}(std::string& result)" "{{ result = \"{1}\"; }}" "\n" ).format(model_name, dm_id) if dm_conj: towrite += ( "\n" "void DarkMatterConj_ID_{0}(std::string& result)" "{{ result = \"{1}\"; }}" "\n\n" ).format(model_name, dm_conj) return towrite
def get_connected_nodes(node_set): """ Recursively return nodes connected to the specified node_set. :param node_set: iterable collection of nodes (list, tuple, set,...) :return: set of nodes with some relationship to the input set. """ search_from = set(node_set) search_found = set() # Very naive algorithm, but we don't anticipate large graphs. while len(search_from) != 0: for node in search_from.copy(): search_found.add(node) search_from.remove(node) for node_relative in node.get_all_parents(): if node_relative not in search_found: search_from.add(node_relative) for node_relative in node.get_all_children(): if node_relative not in search_found: search_from.add(node_relative) return search_found
def create_expr_string(clip_level_value): """Create the expression arg string to run AFNI 3dcalc via Nipype. :type clip_level_value: int :param clip_level_value: The integer of the clipping threshold. :rtype: str :return The string intended for the Nipype AFNI 3dcalc "expr" arg inputs. """ expr_string = "step(a-%s)" % clip_level_value return expr_string
def singleline_diff_format(line1, line2, idx): """ Inputs: line1 - first single line string line2 - second single line string idx - index at which to indicate difference Output: Returns a three line formatted string showing the location of the first difference between line1 and line2. If either input line contains a newline or carriage return, then returns an empty string. If idx is not a valid index, then returns an empty string. """ if len(line1.splitlines()) > 1 or len(line2.splitlines()) > 1: return "" else: output = '' output += line1 + '\n' index = 0 try: idx_1 = int(idx) if idx_1 < 0 or idx_1 > len(line2) or idx_1 > len(line1): raise ValueError except (TypeError, ValueError): return "" while index < idx: output += "=" index += 1 output += "^" + '\n' output += line2 + '\n' return output
def escape_string(arg): """Escape percent sign (%) in the string so it can appear in the Crosstool.""" if arg != None: return str(arg).replace("%", "%%") else: return None
def _get_reduced_shape(shape, params): """ Gets only those dimensions of the coordinates that don't need to be broadcast. Parameters ---------- coords : np.ndarray The coordinates to reduce. params : list The params from which to check which dimensions to get. Returns ------- reduced_coords : np.ndarray The reduced coordinates. """ reduced_shape = tuple(l for l, p in zip(shape, params) if p) return reduced_shape
def asfolder(folder): """ Add "/" at the end of the folder if not inserted :param folder: the folder name :type folder: str :return: file names with / at the end :rtype: str """ if folder[-1] != "/": return (folder + "/") else: return (folder)
def get_printable_cards(cards): """ Return list of string representations of each card in cards. """ return [str(card) for card in cards]
def comprobar(numero): """Comprueba que el valor ingresado sea numerico Si el valor ingresado no es numerico muestra un mensaje de error y vuelve a pedir el valor Tambien sirve para salir del programa si el usuario ingresa la letra 'c' Parametros ---------- numero : valor que sera comprobado """ global flag_exit if numero.lower() == "c": flag_exit = True elif numero.isnumeric(): return numero else: print('\033[91mError: el dato ingresado es incorrecto\033[0m') return comprobar(input())
def srgbToLinearrgb(c): """ >>> round(srgbToLinearrgb(0.019607843), 6) 0.001518 >>> round(srgbToLinearrgb(0.749019608), 6) 0.520996 """ if c < 0.04045: return 0.0 if c < 0.0 else (c * (1.0 / 12.92)) else: return ((c + 0.055) * (1.0 / 1.055)) ** 2.4
def get_from_dom(dom, name): """ safely extract a field from a dom. return empty string on any failures. """ try: fc = dom.getElementsByTagName(name)[0].firstChild if fc is None: return '' else: return fc.nodeValue except Exception as e: return ''
def calculate_rent( product_price: float, minimum_rent_period: int, rent_period: int, discount_rate: float = 0, ) -> float: # noqa E125 """Calculate product rent over period NOTE: "Rent is calculated by multiplying the product's price by the date. If the product has a discount rate and minimum rental period, you need to consider it. Discount can be applied if the user borrows the product beyond the minimum rental period. If a product has no discount rate and only has a minimum rental period, the user can only borrow the product over that minimum rental period." """ if discount_rate < 0 or discount_rate > 1: raise ValueError('Expected `discount_rate` to be in the range [0, 1.0]') if rent_period > minimum_rent_period: rent = round(product_price * (1 - discount_rate) * rent_period, 2) else: rent = round(product_price * minimum_rent_period, 2) return rent
def normalize_mem_info(meminfo): """ Normalize the info available about the memory """ normalized = {'total': meminfo['memtotal']} # If xenial or above, we can look at "memavailable" if 'memavailable' in meminfo: normalized['available'] = meminfo['memavailable'] # Otherwise, we have to math it a little, and it won't be nearly as accurate else: available = \ normalized['total']['value'] - \ meminfo['cached']['value'] - \ meminfo['buffers']['value'] normalized['available'] = { 'value': available, 'unit': normalized['total']['unit'] } normalized['percent_available'] = {'value': ( float(normalized['available']['value']) / float(normalized['total']['value']) ) * 100.0 } return normalized
def choose_amp_backend(use_fp16, native_amp=None, apex_amp=None): """Validate and choose applicable amp backend.""" if use_fp16 not in (True, False, "apex"): raise ValueError("use_fp16 must be a bool or 'apex'.") if not use_fp16: return use_fp16 if use_fp16 == "apex": if not apex_amp: raise ImportError( "Please install apex from " "https://www.github.com/nvidia/apex to use fp16 training " "with apex." ) else: if not native_amp: use_fp16 = "apex" if not apex_amp: raise ImportError( "Neither native PyTorch amp nor apex are available." "Please either upgrade to PyTorch>=1.6 or install apex " "from https://www.github.com/nvidia/apex to use fp16" " training." ) return use_fp16
def i2str(i): """Translate integer coordinates to chess square""" x=7-i//8 y=i % 8 +1 return "ABCDEFGH"[x]+str(y)
def valid_test_filter(_, __, event_dict): """ This is a test filter that is inline with the construction requirements of Structlog processors. If processor ingestion is correct, the corresponding log response will have 'is_valid=True' in the returned event dictionary. Args: event_dict (dict): Logging metadata accumulated Returns: Updated event metadata (dict) """ event_dict['is_valid'] = True return event_dict
def _ensure_bytes_like(thing): """Force an object which may be string-like to be bytes-like Args: thing: something which might be a string or might already be encoded as bytes. Return: Either the original input object or the encoding of that object as bytes. """ try: # check whether thing is bytes-like memoryview(thing) return thing # keep as-is except TypeError: return thing.encode("utf-8")
def bubble(data): """ Ops: O(n^2) """ n = 1 while n < len(data): for i in range(len(data) - n): if data[i] > data[i + 1]: data[i], data[i + 1] = data[i + 1], data[i] n += 1 return data
def parser_DSNG_Descriptor(data,i,length,end): """\ parser_DSNG_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "DSNG", "contents" : unparsed_descriptor_contents } (Defined in ETSI EN 300 468 specification) """ return { "type" : "DSNG", "contents" : data[i+2:end] }
def is_permutation_dict(s1, s2): """Uses a dictionary to store character counts.""" n1 = len(s1) n2 = len(s2) if n1 != n2: return False if s1 == s2: return True ch_count = {} for ch in s1: if ch_count.get(ch, 0) == 0: ch_count[ch] = 1 else: ch_count[ch] += 1 for ch in s2: if ch_count.get(ch, 0) == 0: return False else: ch_count[ch] -= 1 return True
def str_to_bool(val): """Return a boolean for '0', 'false', 'on', ...""" val = str(val).lower().strip() if val in ("1", "true", "on", "yes"): return True elif val in ("0", "false", "off", "no"): return False raise ValueError( "Invalid value '{}'" "(expected '1', '0', 'true', 'false', 'on', 'off', 'yes', 'no').".format(val) )
def is_pangram(string): """ Check if a string is a pangram """ string = string.lower() alphabet = "abcdefghijklmnopqrstuvwxyz" for char in alphabet: if char not in string: return False return True
def dict_apply_listfun(dict, function): """Applies a function that transforms one list to another with the same number of elements to the values in a dictionary, returning a new dictionary with the same keys as the input dictionary, but the values given by the results of the function acting on the input dictionary's values. I.e. if f(x) = x[::-1], then dict_apply_listfun({"a":1,"b":2},f) = {"a":2,"b":1}.""" keys = dict.keys() vals = [dict[key] for key in keys] res = function(vals) return {key: res[i] for i, key in enumerate(keys)}
def render_tag_list(tag_list): """ Inclusion tag for rendering a tag list. Context:: Tag List Template:: tag_list.html """ return dict(tag_list=tag_list)
def _get_optimizer_input_shape(op_type, varkey, orig_shape, param_shape): """ Returns the shape for optimizer inputs that need to be reshaped when Param and Grad is split to multiple servers. """ # HACK(typhoonzero) : Should use functions of corresponding optimizer in # optimizer.py to get the shape, do not bind this in the transpiler. if op_type == "adam": if varkey in ["Moment1", "Moment2"]: return param_shape elif op_type == "adagrad": if varkey == "Moment": return param_shape elif op_type == "adamax": if varkey in ["Moment", "InfNorm"]: return param_shape elif op_type in ["momentum", "lars_momentum"]: if varkey == "Velocity": return param_shape elif op_type == "rmsprop": if varkey in ["Moment", "MeanSquare"]: return param_shape elif op_type == "decayed_adagrad": if varkey == "Moment": return param_shape elif op_type == "ftrl": if varkey in ["SquaredAccumulator", "LinearAccumulator"]: return param_shape elif op_type == "sgd": pass else: raise ValueError( "Not supported optimizer for distributed training: %s" % op_type) return orig_shape
def convert_jump(code): """Convert any give jump code into it's corresponding binary code""" binary = '000' if code is None: return binary elif code == 'JGT': binary = '001' elif code == 'JEQ': binary = '010' elif code == 'JGE': binary = '011' elif code == 'JLT': binary = '100' elif code == 'JNE': binary = '101' elif code == 'JLE': binary = '110' elif code == 'JMP': binary = '111' else: raise ValueError(f"Syntax error, {code} is wrong Jump code!") return binary
def join_summaries(*args): """ Joins summaries. If summary value is not string, it will be ignored. :param str separator: Summary separator. :param list[str] args: List of summaries. :return: Joined strings. :rtype: str | None """ summaries_strings = [] """:type: list[str]""" for summary in args: if isinstance(summary, str) and len(summary) > 0: summaries_strings.append(summary) if len(summaries_strings) == 0: return None return ", ".join(summaries_strings)
def copy_dict(in_dict, def_dict): """Copy a set of key-value pairs to an new dict Parameters ---------- in_dict : `dict` The dictionary with the input values def_dict : `dict` The dictionary with the default values Returns ------- outdict : `dict` Dictionary with only the arguments we have selected """ outdict = {key:in_dict.get(key, val) for key, val in def_dict.items()} return outdict
def find_data_source_url(a_name, url_prefs): """Return the url prefix for data source name, or None.""" for row in url_prefs: if row[0] == a_name: return row[1] return None
def odd(n): """ Counts the number of ODD digits in a given integer/float """ try: if type(n) in [int, float]: return sum([True for d in str(n) if d.isdigit() and int(d) % 2 != 0]) else: raise TypeError("Given input is not a supported type") except TypeError as e: print("Error:", str(e))
def vedHexChecksum(byteData): """ Generate VE Direct HEX Checksum - sum of byteData + CS = 0x55 """ CS = 0x55 for b in byteData: CS -= b CS = CS & 0xFF return CS
def version_from_string(version_str): """ Convert a version string of the form m.n or m.n.o to an encoded version number (or None if it was an invalid format). version_str is the version string. """ parts = version_str.split('.') if not isinstance(parts, list): return None if len(parts) == 2: parts.append('0') if len(parts) != 3: return None version = 0 for part in parts: try: v = int(part) except ValueError: return None version = (version << 8) + v return version