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...
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 ...
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, l...
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: ...
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(...
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 fl...
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']: ...
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':...
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, mi...
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] = s...
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: b...
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:]) re...
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_cy...
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]] ...
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 l...
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 ...
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 ce...
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. """ obs...
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...
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 ...
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('_')...
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: ...
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....
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 cricke...
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()...
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 =...
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:5...
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...
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 re...
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...
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([t...
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']: dock...
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 retu...
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 ...
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_...
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:]) #...
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[m...
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 ...
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: t...
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() #...
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. """ ...
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...
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 -...
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 comprob...
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: re...
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 mult...
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 ha...
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 ap...
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: eve...
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 wheth...
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...
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: ...
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', ...
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...
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 ...
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 == 'JL...
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]""" fo...
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 wit...
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:...
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(...