content
stringlengths
42
6.51k
def set_difference(set_a, set_b): """ compare two sets and return the items which are in set_b but not in set_a """ diff = set_b - set_a return diff
def _remove_function_tags(label): """ Parameters ---------- label: str Returns ------- str """ if "-" in label and not label in ["-NONE-", "-LRB-", "-RRB-", "-LCB-", "-RCB-"]: lst = label.split("-") label = lst[0] if "=" in label: lst = label.split("=") label = lst[0] return label
def replace_variables_from_array(arr, s): """Takes a string and replaces variables in the string with ones from the array #Example: (['R10', '5', 'R1', '7'], 'example string R1 and R10') -> 'example string 7 and 5' :param arr: Array of variables :param s: String to replace variables in :return: String with replaced variables """ for x in range(0, len(arr)-1, 2): # Set increment size to 2. s = s.replace(arr[x], '(' + str(arr[x+1]) + ')') return s
def collect_frequency(simulations): """ Calculates the frequency at which sub processes should collect intermediary results for plotting This is done to ensure that the total number of data points loaded in the charts don't break the matplotlib chart generation. Based on our tests this number seems to be about 7,000 data points """ max_data_points_to_load = 5000 # the max number of data points we allow in the charts # The + 100 at the end is added to round the frequency to the higher 100s. # This is done to ensure that the total number of data points collected is never more than 5000 cf = ((simulations // max_data_points_to_load)//100)*100 + 100 return cf
def _get_branching(container, index): """ Returns the nearest valid element from an interable container. This helper function returns an element from an iterable container. If the given `index` is not valid within the `container`, the function returns the closest element instead. Parameter --------- container: A non-empty iterable object. index: The index of an element that should be returned. Returns ------- object The closest possible element from `container` for `index`. Example ------- The `container` can be an arbitrary iterable object such as a list:: l = ['a', 'b', 'c'] c1 = _get_clamped_index(l, 5) c2 = _get_clamped_index(l, 1) c3 = _get_clamped_index(l, -4) The first call of the function using an index of 5 will return element 'c', the second call will return 'b' and the third call will return 'a'. """ maximal_index = len(container) - 1 minimal_index = 0 clamped_index = min(maximal_index, index) clamped_index = max(minimal_index, clamped_index) return container[clamped_index] # except HttpError as e:
def _process_sort_info(sort_info_lst): """ Split out the zpe and sp sort info """ freq_info = None sp_info = None sort_prop = {} if sort_info_lst is not None: freq_info = sort_info_lst[0] sp_info = sort_info_lst[1] if sort_info_lst[2] is not None: sort_prop['enthalpy'] = sort_info_lst[2] elif sort_info_lst[3] is not None: sort_prop['entropy'] = sort_info_lst[3] elif sort_info_lst[4] is not None: sort_prop['gibbs'] = sort_info_lst[4] else: sort_prop['electronic'] = True return freq_info, sp_info, sort_prop
def unclean_map_javac_to_antlr(javac_token_literal, antlr_literal_rule): """ merge ('TOKEN_ID', 'literal value'), ('literal value', 'RULE_NAME') arrays this is NOT one to one """ copy_javac_tl = list(javac_token_literal) copy_antlr_lt = list(antlr_literal_rule) copy_javac_tl.reverse() copy_antlr_lt.reverse() javac_token_to_antlr_rule = [] literal_partial = "" while len(copy_javac_tl) and len(copy_antlr_lt): (javac_token, javac_literal) = copy_javac_tl.pop() (antlr_literal, antlr_rule) = copy_antlr_lt.pop() # print(javac_literal, antlr_literal, javac_literal == antlr_literal) if javac_literal == antlr_literal: # great, base case, we done javac_token_to_antlr_rule.append((javac_token, antlr_rule,)) literal_partial = "" elif javac_literal == "" and antlr_literal == "<EOF>": javac_token_to_antlr_rule.append((javac_token, antlr_rule,)) literal_partial = "" elif javac_literal == literal_partial + antlr_literal: # constructed literals are okay too javac_token_to_antlr_rule.append((javac_token, antlr_rule)) literal_partial = "" else: # stupid ">" ">>" cases literal_partial += antlr_literal copy_javac_tl.append((javac_token, javac_literal,)) return javac_token_to_antlr_rule
def format(string: str, **kwargs) -> str: """A string formatter example: > n = '$[val]' > val = "Hello, World!" > print(format(n, val=val)) Hello, World! """ for key,val in kwargs.copy().items(): string.replace(f"$[{key}]", val) return string
def dollars_to_changes(dollars, dollar_vals): """Given a dollars amount (e.g. $8.74), and a list of dollar_values in descending values (e.g. [5, 1, 0.50, 0.25, 0.10, 0.05, 0.01]), return a list of tuples of changes. E.g. [(5, 1), (1, 3), (0.5, 1), (0.1, 2), (0.01, 4)] """ cents = int(dollars * 100) res = [] for value in dollar_vals: cval = int(value * 100) n, cents = divmod(cents, cval) if n != 0: res += [(value, n)] return res
def _as_parent_key(parent, key): """Construct parent key.""" if parent: return f"{parent}.{key}" return key
def sort_labels(labels): """Guess what this Sorts the labels :param labels: :type labels: list :return : :rtype : list """ return sorted(labels, key=lambda name: (name[1:], name[0]))
def start(data): """ Get the start coordinate as an int of the data. """ value = data["genome_coordinate_start"] if value: return int(value) return None
def solution1(string): """ :type string: str :rtype: int """ stack = [] score = 0 left = True # `left` indicates the if former symbol is '(' for p in string: if p == '(': stack.append(p) left = True else: stack.pop() if left: score += 2 ** len(stack) left = False return score
def while_condition(string_unsorted_list): """.""" num_lengths = [] for num in string_unsorted_list: num_lengths.append(len(num)) return max(num_lengths)
def get_bool(v): """Get a bool from value.""" if str(v) == '1' or v == 'true' or v is True: return True elif str(v) == '0' or v == 'false' or v is None or v is False: return False else: raise ValueError(f'value {v} was not recognized as a valid boolean')
def parse_filename(fname): """Parse a notebook filename. This function takes a notebook filename and returns the notebook format (json/py) and the notebook name. This logic can be summarized as follows: * notebook.ipynb -> (notebook.ipynb, notebook, json) * notebook.json -> (notebook.json, notebook, json) * notebook.py -> (notebook.py, notebook, py) * notebook -> (notebook.ipynb, notebook, json) Parameters ---------- fname : unicode The notebook filename. The filename can use a specific filename extention (.ipynb, .json, .py) or none, in which case .ipynb will be assumed. Returns ------- (fname, name, format) : (unicode, unicode, unicode) The filename, notebook name and format. """ if fname.endswith('.ipynb'): format = 'json' elif fname.endswith('.json'): format = 'json' elif fname.endswith('.py'): format = 'py' else: fname = fname + '.ipynb' format = 'json' name = fname.split('.')[0] return fname, name, format
def decomposeQuadraticSegment(points): """Split the quadratic curve segment described by 'points' into a list of "atomic" quadratic segments. The 'points' argument must be a sequence with length 2 or greater, containing (x, y) coordinates. The last point is the destination on-curve point, the rest of the points are off-curve points. The start point should not be supplied. This function returns a list of (pt1, pt2) tuples, which each specify a plain quadratic bezier segment. """ n = len(points) - 1 assert n > 0 quadSegments = [] for i in range(n - 1): x, y = points[i] nx, ny = points[i+1] impliedPt = (0.5 * (x + nx), 0.5 * (y + ny)) quadSegments.append((points[i], impliedPt)) quadSegments.append((points[-2], points[-1])) return quadSegments
def _filter_empty_field(data_d): """ Remove empty lists from dictionary values Before: {'target': {'CHECKSUM': {'checksum-fill': []}}} After: {'target': {'CHECKSUM': {'checksum-fill': ''}}} Before: {'tcp': {'dport': ['22']}}} After: {'tcp': {'dport': '22'}}} """ for k, v in data_d.items(): if isinstance(v, dict): data_d[k] = _filter_empty_field(v) elif isinstance(v, list) and len(v) != 0: v = [_filter_empty_field(_v) if isinstance(_v, dict) else _v for _v in v] if isinstance(v, list) and len(v) == 1: data_d[k] = v.pop() elif isinstance(v, list) and len(v) == 0: data_d[k] = '' return data_d
def get_prefix_less_name(element): """ Returns a prefix-less name :param elements: element top use on the search :type elements: str :return: The prefix-less name :rtype: str """ return element.split("|")[-1].split(":")[-1]
def parse_stock_code(code: str): """Parses a stock code. NOTE: Only works for the Shinhan HTS""" if code.startswith("A"): return code[1:] elif code == "": return None else: return code
def escape_string(value: str) -> str: """ Escape control characters""" if value: return value.replace("\n", "\\n").replace("\r", "").replace('"', "'") return ""
def order_data(data, byte_order): """ Reordena los datos segun el byte_order de la variable/item """ A_inx = byte_order.index("A") if "A" in byte_order else 0 B_inx = byte_order.index("B") if "B" in byte_order else 0 C_inx = byte_order.index("C") if "C" in byte_order else 0 D_inx = byte_order.index("D") if "D" in byte_order else 0 reordered = data if len(data) == 1: return reordered if len(data) == 2: if B_inx < A_inx: reordered = bytes([data[1], data[0]]) if len(data) == 4: reordered = [1] * 4 reordered[0] = data[A_inx] reordered[1] = data[B_inx] reordered[2] = data[C_inx] reordered[3] = data[D_inx] reordered = bytes(reordered) if len(data) == 8: if A_inx != 0: reordered = [1] * 8 reordered[0] = data[7] reordered[1] = data[6] reordered[2] = data[5] reordered[3] = data[4] reordered[4] = data[3] reordered[5] = data[2] reordered[6] = data[1] reordered[7] = data[0] reordered = bytes(reordered) return reordered
def xor(a, b): """ Renvoie a xor b. """ x = [False]*len(a) for i in range(len(a)): x[i] = a[i] ^ b[i] return x
def add(u, v): """ Returns the vector addition of vectors u + v """ if len(u) != len(v): raise ValueError("Vectors lengths differ {} != {}".format(len(u), len(v))) return tuple(e + g for e, g in zip(u, v))
def search_person(lista, nombre): """ Buscar persona en lista de personas. Buscamos un nombre en una lista de instancias de la clase Person. En caso de que se encuentre regresamos su indica, en otro caso regresamos -1 Hay que tener cuidado con este valor porque -1 es un valor que se puede pasar como indice, pero esta funcon lo regresa como indicador de que no encontro lo que se buscaba """ if nombre != None: for i in range(len(lista)): if lista[i].nombre == nombre: return i return -1
def remove(text, targets): """.""" for key, val in targets.items(): if key in text: text = text.replace(key, '', val) return text
def convert_time_to_hour_minute(hour, minute, convention): """ Convert time to hour, minute """ if hour is None: hour = 0 if minute is None: minute = 0 if convention is None: convention = 'am' hour = int(hour) minute = int(minute) if convention.lower() == 'pm': hour += 12 return {'hours': hour, 'minutes': minute}
def dump_rank_records(rank_records, out_fp, with_rank_idx): """ each line is ranking sid score sid: config.SEP.join((doc_idx, para_idx, sent_idx)) :param sid_score_list: :param out_fp: :return: """ lines = rank_records if with_rank_idx: lines = ['\t'.join((str(rank), record)) for rank, record in enumerate(rank_records)] with open(out_fp, mode='a', encoding='utf-8') as f: f.write('\n'.join(lines)) return len(lines)
def is_asking_nextEvent(text): """ Checks if user is asking for next event. Parameters: text (string): user's speech Returns: (bool) """ state = False keyword = [ "event", "events", "timetable", "class" ] for word in keyword: if ((text.lower()).find(word.lower()) != -1): state = True return state
def format_text(text): """ Foramt text """ string = "" for i in text: string += i return string
def getTokenType(hueChange: int, lightChange: int) -> str: """ Find the toColorToken type based on hue change and lightness change :param hueChange: number of hue changes between two pixels :param lightChange: number of lightness changes between two pixels :return: A string with the toColorToken type """ tokens = [ ["noop", "push", "pop"], ["add", "subtract", "multiply"], ["divide", "mod", "not"], ["greater", "pointer", "switch"], ["duplicate", "roll", "inN"], ["inC", "outN", "outC"], ] return tokens[hueChange][lightChange]
def _service_account_name(service_acct_email): """Gets an IAM member string for a service account email.""" return 'serviceAccount:{}'.format(service_acct_email)
def remove_empty_elements(value): """ Recursively remove all None values from dictionaries and lists, and returns the result as a new dictionary or list. """ if isinstance(value, list): return [remove_empty_elements(x) for x in value if x is not None] elif isinstance(value, dict): return { key: remove_empty_elements(val) for key, val in value.items() if val is not None } else: return value
def is_number(s): """ Returns True is string is a number. """ try: float(s) return True except ValueError: return False
def t_and_beta_to_varcope(t, beta): """Convert t-statistic to sampling variance using parameter estimate. .. versionadded:: 0.0.4 Parameters ---------- t : array_like T-statistics of the parameter beta : array_like Parameter estimates Returns ------- varcope : array_like Sampling variance of the parameter """ varcope = (beta / t) ** 2 return varcope
def scale_frame_size(frame_size, scale): """Scales the frame size by the given factor. Args: frame_size: a (width, height) tuple scale: the desired scale factor Returns: the scaled (width, height) """ return tuple(int(round(scale * d)) for d in frame_size)
def x_www_form_urlencoded(post_data): """ convert origin dict to x-www-form-urlencoded Args: post_data (dict): {"a": 1, "b":2} Returns: str: a=1&b=2 """ if isinstance(post_data, dict): return "&".join([ u"{}={}".format(key, value) for key, value in post_data.items() ]) else: return post_data
def sparse_clip_norm(parameters, max_norm, norm_type=2): """Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Supports sparse gradients. Parameters ---------- parameters : ``(Iterable[torch.Tensor])`` An iterable of Tensors that will have gradients normalized. max_norm : ``float`` The max norm of the gradients. norm_type : ``float`` The type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns ------- Total norm of the parameters (viewed as a single vector). """ # pylint: disable=invalid-name,protected-access parameters = list(filter(lambda p: p.grad is not None, parameters)) max_norm = float(max_norm) norm_type = float(norm_type) if norm_type == float('inf'): total_norm = max(p.grad.data.abs().max() for p in parameters) else: total_norm = 0 for p in parameters: if p.grad.is_sparse: # need to coalesce the repeated indices before finding norm grad = p.grad.data.coalesce() param_norm = grad._values().norm(norm_type) else: param_norm = p.grad.data.norm(norm_type) total_norm += param_norm ** norm_type total_norm = total_norm ** (1. / norm_type) clip_coef = max_norm / (total_norm + 1e-6) if clip_coef < 1: for p in parameters: if p.grad.is_sparse: p.grad.data._values().mul_(clip_coef) else: p.grad.data.mul_(clip_coef) return total_norm
def ipv4_arg_to_bin(w, x, y, z): """Generate unsigned int from components of IP address returns: w << 24 | x << 16 | y << 8 | z""" return (w << 24) | (x << 16) | (y << 8) | z
def str_to_int(string): """Solution to exercise R-4.7. Describe a recursive function for converting a string of digits into the integer it represents. For example, "13531" represents the integer 13,531. """ n = len(string) zero_unicode = ord('0') def recurse(idx): if idx == n: return 0 # Base case int_val = ord(string[idx]) - zero_unicode return int_val * 10 ** (n - 1 - idx) + recurse(idx + 1) return recurse(0)
def _HexToSignedInt(hex_str): """Converts a hex string to a signed integer string. Args: hex_str: A string representing a hex number. Returns: A string representing the converted signed integer. """ int_val = int(hex_str, 16) if int_val & (1 << 31): int_val -= 1 << 32 return str(int_val)
def sum_square_difference(n: int) -> int: """ Returns the "sum square difference" of the first n natural numbers. """ square_of_sum = (n*(n+1) // 2)**2 sum_of_squares = n*(n+1)*(2*n+1) // 6 return square_of_sum - sum_of_squares
def islamic_date(year, month, day): """Return an Islamic date data structure.""" return [year, month, day]
def audio_len(audio): """ >>> audio_len(([1, 2, 3], [4, 5, 6])) 3 """ (left, right) = audio assert len(left) == len(right) return len(left)
def FIT(individual): """Sphere test objective function. F(x) = sum_{i=1}^d x_i^2 d=1,2,3,... Range: [-100,100] Minima: 0 """ y = sum(x**2 for x in individual) return y
def check_roles(role_required, role_list): """Verify string is within the list. :param string role_required: The string to find :param list role_list: The list of user roles :return boolean: True or False based on whether string was found """ for index, role in enumerate(role_list): if role.name in role_required: return True return False
def process_group(grp): """ Given a list of tokens of tokens where the first row is a number and the second (also last) row contains an `x` or a number separated by ',' , compute the product of additive inverse of some minimum modular residue with its corresponding value from the second row. :param grp: The list of list of tokens. :return: The product of the minimum residue with its corresponding value from the second row. """ # Get the time of the earliest bus. e_time = int(grp[0]) # Extract all the important bus times. bus_ids = list(map(int, [x for x in grp[1].split(",") if x != "x"])) # Find the minimum value for bus - (e_time % bus) over all buses. # Also keep a track of the corresponding bus # as a second component in tuple. ans = min([(bus - (e_time % bus), bus) for bus in bus_ids]) # Return their product. return ans[0] * ans[1]
def logEq(a, b): """Returns 1 if the logical value of a equals the logical value of b, 0 otherwise""" return (not a) == (not b)
def get_attempt_data(all_gens): """ Extracts the attempt data of succesful generations all_gens - dict of key nodeID value list of (nodeID, createTime, attempts, (createID, sourceID, otherID, mhpSeq)) :return: dict of dicts A dict with keys being nodeIDs and values being dictinoaries of the form {Entanglement ID: Number of generation attempts} """ gen_attempts = {} for nodeID, all_node_gens in all_gens.items(): for gen in all_node_gens: attempts = gen[2] ent_id = gen[-3:] key = "{}_{}_{}".format(*ent_id) if nodeID in gen_attempts: gen_attempts[nodeID][key] = attempts else: gen_attempts[nodeID] = {key: attempts} # For consistent output, create empty dict if no gens if len(gen_attempts) == 0: gen_attempts = {0: {}, 1: {}} if len(gen_attempts) == 1: if list(gen_attempts.keys())[0] == 0: gen_attempts[1] = {} else: gen_attempts[0] = {} return gen_attempts
def context_combination( windows, use_docker, use_celery, use_mailhog, use_sentry, use_whitenoise, cloud_provider, ): """Fixture that parametrize the function where it's used.""" return { "windows": windows, "use_docker": use_docker, "use_celery": use_celery, "use_mailhog": use_mailhog, "use_sentry": use_sentry, "use_whitenoise": use_whitenoise, "cloud_provider": cloud_provider, }
def selection_sort(arr: list) -> list: """Sort a list using selection sort Args: arr (list): the list to be sorted Returns: list: the sorted list """ size = len(arr) # Loop over entire array except the last element for j in range(size - 1): # Set the current minimum index to j iMin = j # Loop over the unsorted array (starting at j + 1) for i in range(j + 1, size): # Change the minimum when the number is smaller if arr[i] < arr[iMin]: iMin = i # If they aren't the same # Swap the minimum and the first element in the unsorted array if iMin != j: arr[j], arr[iMin] = arr[iMin], arr[j] return arr
def move_id_ahead(element_id, reference_id, idstr_list): """Moves element_id ahead of reference_id in the list""" if element_id == reference_id: return idstr_list idstr_list.remove(str(element_id)) reference_index = idstr_list.index(str(reference_id)) idstr_list.insert(reference_index, str(element_id)) return idstr_list
def _LJ_ab_to_rminepsilon(coeffs): """ Convert AB representation to Rmin/epsilon representation of the LJ potential """ if (coeffs['A'] == 0.0 and coeffs['B'] == 0.0): return {"sigma": 0.0, "epsilon": 0.0} try: Rmin = (2.0 * coeffs['A'] / coeffs['B'])**(1.0 / 6.0) Eps = coeffs['B']**2.0 / (4.0 * coeffs['A']) except ZeroDivisionError: raise ZeroDivisionError("Lennard Jones functional form conversion not possible, division by zero found.") return {"Rmin": Rmin, "epsilon": Eps}
def tail(list, n): """ Return the last n elements of a list """ return list[:n]
def re_escape(string: str) -> str: """ Escape literal backslashes for use with re. :param string: :type string: :return: :rtype: """ return string.replace('\\', "\\\\")
def tip(bill): """Adds 15% tip to a restaurant bill.""" bill *= 1.15 print ("With tip: %f" % bill) return bill
def _combined_lists(alist, total=None): """ Given a list of lists, make that set of lists one list """ if total is None: total = [] if not alist: return total return _combined_lists(alist[1:], total + alist[0])
def _map_abbreviations(text: str, abbrevs: dict) -> str: """Maps the abbreviations using the abbrevs side input.""" output = [] space = " " for word in text.split(space): if word in abbrevs: output.append(abbrevs[word]) else: output.append(word) return space.join(output)
def _invert_signs(signs): """ Shall we invert signs? Invert if first (most probable) term is negative. """ return signs[0] < 0
def setPercentage(pt): """ @param pt: The new percentage threshold @type pt: Float between 1 and 100 @return: 1 value is not correct """ if 1 <= pt <= 100: global PERCENTAGE PERCENTAGE = pt else: return 1
def permissions_string(permissions, known_permissions): """Return a comma separated string of permission changes. :param permissions: A list of strings, or ``None``. These strings can exclusively contain ``+`` or ``-`` prefixes, or contain no prefixes at all. When prefixed, the resulting string will simply be the joining of these inputs. When not prefixed, all permissions are considered to be additions, and all permissions in the ``known_permissions`` set that aren't provided are considered to be removals. When None, the result is `+all`. :param known_permissions: A set of strings representing the available permissions. """ to_set = [] if permissions is None: to_set = ['+all'] else: to_set = ['-all'] omitted = sorted(known_permissions - set(permissions)) to_set.extend('-{}'.format(x) for x in omitted) to_set.extend('+{}'.format(x) for x in permissions) return ','.join(to_set)
def extract_helm_from_json(input_json): """Extracts the HELM strings out of a JSON array. :param input_json: JSON array of Peptide objects :return: output_helm: string (extracted HELM strings separated by a newline) """ output_helm = "" for peptide in input_json: if len(output_helm) > 0: output_helm += "\n" output_helm += peptide["HELM"] return output_helm
def uniform(n): """ Initializer for a uniform distribution over n elements n :: int """ return [1 / n for _ in range(n)]
def remove_non_printable_chars(string): """Remove non-ASCII chars like chinese chars""" printable = set( """0123456789abcdefghijklmnopqrstuvwxyz""" """ABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ """ ) return "".join(filter(lambda x: x in printable, string))
def shorten(text, width, suffix='...'): """Truncate the given text to fit in the given width.""" if len(text) <= width: return text if width > len(suffix): return text[:width-len(suffix)] + suffix if width >= 0: return suffix[len(suffix)-width:] raise ValueError('width must be equal or greater than 0')
def device_settings(string): """Convert string with SoapySDR device settings to dict""" if not string: return {} settings = {} for setting in string.split(','): setting_name, value = setting.split('=') settings[setting_name.strip()] = value.strip() return settings
def zeros_matrix(rows, cols): """ Creates a matrix filled with zeros. :param rows: the number of rows the matrix should have :param cols: the number of columns the matrix should have :returns: list of lists that form the matrix. """ M = [] while len(M) < rows: M.append([]) while len(M[-1]) < cols: M[-1].append(0.0) return M
def evaluate(x, poly): """ Evaluate the polynomial at the value x. poly is a list of coefficients from lowest to highest. :param x: Argument at which to evaluate :param poly: The polynomial coefficients, lowest order to highest :return: The result of evaluating the polynomial at x """ if len(poly) == 0: return 0 else: return x*evaluate(x,poly[1:]) + poly[0]
def get_imaging_maskbits(bitnamelist=None): """Return MASKBITS names and bits from the Legacy Surveys. Parameters ---------- bitnamelist : :class:`list`, optional, defaults to ``None`` If not ``None``, return the bit values corresponding to the passed names. Otherwise, return the full MASKBITS dictionary. Returns ------- :class:`list` or `dict` A list of the MASKBITS values if `bitnamelist` is passed, otherwise the full MASKBITS dictionary of names-to-values. Notes ----- - For the definitions of the mask bits, see, e.g., https://www.legacysurvey.org/dr8/bitmasks/#maskbits """ bitdict = {"BRIGHT": 1, "ALLMASK_G": 5, "ALLMASK_R": 6, "ALLMASK_Z": 7, "BAILOUT": 10, "MEDIUM": 11, "GALAXY": 12, "CLUSTER": 13} # ADM look up the bit value for each passed bit name. if bitnamelist is not None: return [bitdict[bitname] for bitname in bitnamelist] return bitdict
def _parse_volumes_kwarg(cli_style_volumes): """ The Python API for mounting volumes is tedious. https://github.com/docker/docker-py/blob/master/docs/volumes.md This makes it work like the CLI """ binds = {} volumes = [] for volume in cli_style_volumes: split = volume.split(':') if len(split) == 1: volume.append(split[0]) continue host_path = split[0] mountpoint = split[1] if len(split) == 3: read_only = split[2] == 'ro' else: read_only = False volumes.append(mountpoint) binds[host_path] = {'bind': mountpoint, 'ro': read_only} return volumes, binds
def finder3(l1, l2): """ Find the missing element in a non-python specific approach in constant space complexity. """ result = 0 for num in l1 + l2: result ^= num return result
def subs(string: str, *args: tuple, **kwargs: dict) -> bytes: """Function to take ``string``, format it using ``args`` and ``kwargs`` and encode it into bytes. Args: string (str): string to be transformed. Returns: bytes: the resulting bytes. """ return string.format(*args, **kwargs).encode('latin')
def sieve_of_eratosthenes(n): """sieve_of_eratosthenes(n): return the list of the primes < n.""" if n <= 2: return [] sieve = list(range(3, n, 2)) top = len(sieve) for si in sieve: if si: bottom = (si*si - 3) // 2 if bottom >= top: break sieve[bottom::si] = [0] * -((bottom - top) // si) return [2] + [el for el in sieve if el]
def generate_legend(legendurl): """Generate legend """ overlaycoords = ''' <ScreenOverlay> <name>Legend image</name> <Icon> <href>%s</href> </Icon> <overlayXY x="0.02" y="0.02" xunits="fraction" yunits="fraction" /> <screenXY x="0.02" y="0.02" xunits="fraction" yunits="fraction" /> <rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction" /> <size x="-1" y="-1" xunits="pixels" yunits="pixels" /> </ScreenOverlay> ''' return overlaycoords % legendurl
def aterm(f,p,pv0,e,B,R,eta): """ For the cubic equation for nu in the four-variable model with CRISPR, this is the coefficient of nu^3 """ return B*e**2*f*p*pv0**2*(-1 + f + R)
def merger(l): """ This function takes a list of strings as a parameter and return list of grouped, consecutive strings :param l: List of strings :return: """ if not l: print("Error in merge with empty list") elif len(l) == 1: return l else: # Divide the list from half half_length = int(len(l) / 2) left = merger(l[:half_length]) right = merger(l[half_length:]) if left[-1][-1] == right[0][0]: # If left and right have common string from ending and beginning respectively, merge them return left[:-1] + [left[-1] + right[0]] + right[1:] else: # Else return directly return left + right
def priority(x, y, goal): """Priority for a State.""" return abs(goal[0] - x) + abs(goal[1] - y)
def remove_overlapping_ems(mentions): """ Spotlight can generate overlapping EMs. Among the intersecting EMs, remove the smaller ones. """ to_remove = set() new_mentions = [] length = len(mentions) for i in range(length): start_r = mentions[i]['start'] end_r = mentions[i]['end'] for j in range(length): if i != j and j not in to_remove: start = mentions[j]['start'] end = mentions[j]['end'] if start_r >= start and end_r <= end: to_remove.add(i) for i in range(length): if i not in to_remove: new_mentions.append(mentions[i]) return new_mentions
def non_zero_push_left(line): """ This function pushes non-zero numbers to the left and returns a new list after filling the zeros in place of the pushed numbers It takes O(n) time --> linear run-time complexity :param line: :return line_copy: """ line_copy = [] zero_counter = 0 for num in line: if num != 0: line_copy.append(num) else: zero_counter += 1 for index in range(zero_counter): line_copy.append(0) return line_copy
def parse_minus(data): """Parse minus sign from raw multimeter data :param data: Raw multimeter data, aligned to 15-byte boundary :type data: bytes :return: Whether minus is on :rtype: bool """ return bool(data[3] & 1)
def str_to_int(value): """Converts an input string into int value, or returns input if input is already int Method curated by Anuj Som Args: value (int, str): Accepts an int or string to convert to int Returns: tuple (int, bool): returns (integer value, True) if conversion success returns (-1,False) if conversion failed """ if(type(value) == int): return (value, True) try: int_val = int(value) except ValueError: return (-1, False) return (int_val, True)
def define_tuner_hparam_space(hparam_space_type): """Define tunable hparams for grid search.""" if hparam_space_type not in ('pg', 'pg-topk', 'topk', 'is'): raise ValueError('Hparam space is not valid: "%s"' % hparam_space_type) # Discrete hparam space is stored as a dict from hparam name to discrete # values. hparam_space = {} if hparam_space_type in ('pg', 'pg-topk', 'is'): # Add a floating point parameter named learning rate. hparam_space['lr'] = [1e-5, 1e-4, 1e-3] hparam_space['entropy_beta'] = [0.005, 0.01, 0.05, 0.10] else: # 'topk' # Add a floating point parameter named learning rate. hparam_space['lr'] = [1e-5, 1e-4, 1e-3] hparam_space['entropy_beta'] = [0.0, 0.005, 0.01, 0.05, 0.10] if hparam_space_type in ('topk', 'pg-topk'): # topk tuning will be enabled. hparam_space['topk'] = [10] hparam_space['topk_loss_hparam'] = [1.0, 10.0, 50.0, 200.0] elif hparam_space_type == 'is': # importance sampling tuning will be enabled. hparam_space['replay_temperature'] = [0.25, 0.5, 1.0, 2.0] hparam_space['alpha'] = [0.5, 0.75, 63 / 64.] return hparam_space
def notifier_title_cleaner(otitle): """ Simple function to replace problematic Markdown characters like `[` or `]` that can mess up links. These characters can interfere with the display of Markdown links in notifications. :param otitle: The title of a Reddit post. :return otitle: The cleaned-up version of the same title with the problematic characters escaped w/ backslashes. """ # Characters to prefix a backslash to. specific_characters = ["[", "]"] for character in specific_characters: if character in otitle: otitle = otitle.replace(character, r"\{}".format(character)) return otitle
def UnCapitalize(name): """Uncapitalize a name""" if name: return name[0].lower() + name[1:] else: return name
def clip_location(position): """Clip a postion for a BioPython FeatureLocation to the reference. WARNING: Use of reference length not implemented yet. """ return max(0, position)
def slicetime(mat): """return two matrices, one with only time and the other with the rest of the matrice""" return [row[0:1] for row in mat], [row[1:] for row in mat]
def speed_converter(miles_per_min): """ >>> speed_converter(0) 0.0 >>> speed_converter(0.5) 1158.48 >>> speed_converter(0.75) 1737.72 >>> speed_converter(2) 4633.92 """ kilos_per_day =miles_per_min*1.609*24*60 return kilos_per_day
def duration360days(Ndays): """ Convers a number o days into duration tuple (years, months, days) in a 360/30 day counting convention. :param Ndays: Number of days :return: Tuple (years, monhts, days) :type Ndays: int :rtype: tuple(int, int, int) Example: >>> from m2py.finance import dtime as dt >>> dt.duration360days(1321) >>> (3, 8, 1) 1321 days = 3 years, 8 months and 1 day """ years = int(Ndays / 360) rem = Ndays % 360 months = int(rem / 30) days = rem % 30 return (years, months, days)
def validate_output(err, count, snr, shr, rnd, crd): """ Clean and validate output data - Remove measurements with unphysical values, such as negative countrate - Remove low information entries, such as magnitude errors >0.5 & SNR <1 - Remove missing value indicators such as +/- 9.99 """ return (err < 0.5) & (count >= 0) & (snr >= 1) & (crd != 9.999) & \ (shr != 9.999) & (shr != -9.999) & (rnd != 9.999) & (rnd != -9.999)
def get_codec_name(args, codec_type='video'): """ Search list of arguments for the codec name. :param args: list of ffmpeg arguments :param codec_type: string, type of codec to check for. :returns: string, name of codec. """ try: query = '-codec:v' if codec_type == 'video' else '-codec:a' codec_index = args.index(query) + 1 except ValueError: return '' return args[codec_index]
def colorscale_to_colors(colorscale): """ Extracts the colors from colorscale as a list """ color_list = [] for item in colorscale: color_list.append(item[1]) return color_list
def merge_coverage(old, new): # type: (str, str) -> str """Merge two coverage strings. Each of the arguments is compact coverage data as described for get_coverage_by_job_ids(), and so is the return value. The merged string contains the 'stronger' or the two corresponding characters, where 'C' defeats 'U' and both defeat 'N'. """ cov_data = [] for lineno in range(max(len(old), len(new))): try: old_cov = old[lineno] except IndexError: old_cov = 'N' try: new_cov = new[lineno] except IndexError: new_cov = 'N' if old_cov == 'C' or new_cov == 'C': cov_data.append('C') elif old_cov == 'U' or new_cov == 'U': cov_data.append('U') else: cov_data.append('N') return ''.join(cov_data)
def tabContentState(state): """Returns css selector based on tab content state""" return 'active' if state else 'fade'
def to_grid(tiles): """ Organizes a list of tiles into a matrix that can be iterated over. """ tiles = sorted(tiles, key=lambda elem: elem.x) pivot = 1 for idx, element in enumerate(tiles): if idx == 0: continue prior_element = tiles[idx-1] if element.x != prior_element.x: pivot = idx break return [tiles[i:i+pivot] for i in range(0, len(tiles), pivot)]
def align_buf(buf: bytes, sample_width: int): """In case of buffer size not aligned to sample_width pad it with 0s""" remainder = len(buf) % sample_width if remainder != 0: buf += b'\0' * (sample_width - remainder) return buf
def get_chart_data(tick, nodes, prev_nodes): """ Generates chart data for current tick using enumerated data for all reachable nodes. """ data = { 't': tick, 'nodes': len(nodes), 'ipv4': 0, 'ipv6': 0, 'user_agents': {}, 'countries': {}, 'coordinates': {}, 'orgs': {}, 'join': 0, 'leave': 0, } curr_nodes = set() for node in nodes: # 0: address # 1: port # 2: version # 3: user_agent # 4: timestamp # 5: start_height # 6: hostname # 7: city # 8: country # 9: latitude # 10: longitude # 11: timezone # 12: asn # 13: org address = node[0] port = node[1] user_agent = node[3] country = node[8] latitude = node[9] longitude = node[10] org = node[13] curr_nodes.add((address, port)) if ":" in address: data['ipv6'] += 1 else: data['ipv4'] += 1 data['user_agents'][user_agent] = data['user_agents'].get( user_agent, 0) + 1 data['countries'][country] = data['countries'].get(country, 0) + 1 coordinate = "%s,%s" % (latitude, longitude) data['coordinates'][coordinate] = data['coordinates'].get( coordinate, 0) + 1 data['orgs'][org] = data['orgs'].get(org, 0) + 1 data['join'] = len(curr_nodes - prev_nodes) data['leave'] = len(prev_nodes - curr_nodes) return data, curr_nodes
def is_list(value): """ Returns True if the given value is a list-like instance >>> is_list([1, 2, 3]) True >>> is_list(u'2') False """ return isinstance(value, (list, tuple, set))
def column(tabular, n): """get nth column from tabular data """ col = [] for row in tabular: if len(row) < n+1: col.append("") else: col.append(row[n]) return col
def dict_remove(x, exclude=[]): """Remove items from a dict.""" return dict((k, v) for k, v in x.items() if k not in exclude)
def get_url(id: str): """ Converts video id into url for the video. """ url = "https://youtu.be/" + id return url