content
stringlengths
42
6.51k
def _stable_hash(s): """A simple string hash that won't change from run to run.""" ret = 0 for c in s: ret = ret * 97 + ord(c) return ret
def tolist(textlist): """ ' a, b,c,d, e,f ' -> [a, b, c, d, e, f]""" return [x.strip() for x in textlist.split(",")] if textlist else []
def fasta_formatted_string(name, sequence, description=None, line_width=None): """Returns the name and character sequence in the FASTA format. Parameters ---------- name : str Name describing the sequence. Usually the ID in the sequence in the a FASTA file. sequence : str Characters...
def replace_all(text, dic, filtered=None): """ Searches for specific keys in TEXT and replaces them with the value from DIC. Uses a dictionary to find specific keys and replace them with the relevant value pair. DIC holds the key:value look up information. Args: text: is an iterabl...
def var_is_false(var): """ Returns True if var = False, else False. Remember here that 1 is a almost True value but in this case should return False. :param var: any variable. :return: boolean """ return not var and isinstance(var, bool)
def is_reachable(peer): """ Return true if the peer has an endpoint i.e. it is reachable from the outside. In other words, returns false for dynamic peers """ return "endpoint" in peer
def swap_uuid_prefix_and_suffix(uuid_string: str) -> str: """Swap the first 12 and last 12 hex digits of a uuid string. Different databases implement uuid comparison differently (see UUIDOrdering). This function is useful as a helper method to implement the LastSixBytesFirst ordering method based on the ...
def getSpectroscopicParmLabel(expt_type): """ Returns the label for the spectroscopic parameter in the plot group. Parameters ---------- expt_type : str Type of the experiment - found in the parms.txt file Returns ------- str label for the spectroscopic paramet...
def _convert_pascal_to_camel(pascal_case_string: str) -> str: """ Convert a string provided in PascalCase to camelCase """ return pascal_case_string[:1].lower() + pascal_case_string[1:]
def _get_python_function_arguments(f): """ Helper to get the parameter names and annotations of a Python function. """ # Note that we only return non-optional arguments (we assume that any optional args are not specified). # This allows to, e.g., accept max(a, b, *more, name='') as a binary function...
def rewrite_path(path, template): """Converts source path to destination path based on template :param path: string, example: a.#0.name :param template: template string, example: b.*.name :return: string, example: b.#0.name """ path_parts = path.split('.') template_parts = template.split('....
def change_digits(digits, num): """Change digits by num""" n = len(digits) - 1 digits[n] += num while digits[n] < 0: while digits[n] < 0: digits[n] += 10 digits[n - 1] -= 1 n -= 1 return digits
def create_callback_zone(action, num): """ Create the callback data associated to each button""" return ";".join([action, str(num)])
def parse_nick(name): """ parse a nickname and return a tuple of (nick, mode, user, host) <nick> [ '!' [<mode> = ] <user> ] [ '@' <host> ] """ try: nick, rest = name.split('!') except ValueError: return (name, None, None, None) try: mode, rest = rest.split('=') exce...
def rotate_right(head, k): """ Rotate the given linked list to the right by k places :param head: head node of given linked list :type head: ListNode :param k: position to rotate :type k: int :return: head node of rotated linked list :rtype: Node """ # basic case if head is ...
def user_can_create_edit_delete(user, obj): """A simple function to see if a user is authorized to create, edit, or update events or upload event objects. Great Lakes stocking Coordinator (based at USWFS Green Bay Office) can create, edit, or delete anyone's event (True). Agency Stocking Corrdinaors a...
def test_callback(container, text=''): """ A callback used for basic testing. """ return { 'actions': [ { 'action': 'chat.postMessage', 'kwargs': { 'text': '{}'.format(text) } } ] }
def padding_format(padding): """ Checks that the padding format correspond format. Parameters ---------- padding : str Must be one of the following:"same", "SAME", "VALID", "valid" Returns ------- str "SAME" or "VALID" """ if padding in ["SAME", "same"]: pa...
def sigmoid_derivative(x): """ Actual derivative: S'(x) = S(x)(1-S(x)) but the inputs have already gone through the sigmoid function. """ return x * (1 - x)
def GetMinValue(list): """Get the min value in a list. Args: list: a value list. Returns: the min value in the list. """ minv = list[0] for x in list: if x < minv: minv = x return minv
def bin_data(x, t, bin_width, bin_start): """ Bin data. Bin the provided data into evenly-distributed time bins. """ # Define time grid t_bins = [] x_bins = [] # Iterate through time bins return x_bins, t_bins
def forcetoint(src) -> int: """Forces the input value to an int, on error, returns 0""" try: return int(src) except Exception: return 0
def append_slash(dev): """Append a final slash, if needed.""" if not dev.endswith("/"): dev += "/" return dev
def binding_str(binding): """Handles string conversion of either dictionary or Unifier.""" if isinstance(binding, dict): s = ",".join(["{}: {}".format(str(var), str(val)) for var, val in binding.items()]) return '{' + s + '}' else: return str(binding)
def get_key_recursive(search_dict, field): """ Takes a dict with nested lists and dicts, and searches all dicts for a key of the field provided. - modified from: https://stackoverflow.com/a/20254842 """ fields_found = [] for key, value in search_dict.items(): if key == field: ...
def split(versionstring): """Split the version string 'X.Y.Z' and return tuple (int(X), int(Y), int(Z))""" assert versionstring.count('.') == 2, "Version string must be of the form str('X.Y.Z')" return tuple([int(x) for x in versionstring.split('.')])
def _MethodCallRepr(message): """Gives a string representation of |obj|.|method|(*|args|, **|kwargs|) Args: message: A MetricCall object. """ if not message: return repr(message) obj = message.metric_name method = message.method args = message.method_args kwargs = message.method_kwargs args_...
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values)
def create_environment(**kwargs): """ Format args for AWS environment Writes argument pairs to an array {name, value} objects, which is what AWS wants for environment overrides. """ return [{'name': k, 'value': v} for k, v in kwargs.items()]
def set_indent(x: str, n: int = 2): """ Args: x: n: Returns: """ indent = ' ' * n x = indent + x x = x.replace('\n', '\n' + indent) return x
def normalize_ensembl_genes(ensgenes): """ :param ensgenes: :return: """ ens_genes = [] for ensid, trans in ensgenes.items(): strands = set(t['strand'] for t in trans) assert len(strands) == 1, 'Switching strands: {}'.format(trans) strand = strands.pop() feat_type...
def le_calibration_func(etr, kc, ts): """Latent heat flux at the calibration points Parameters ---------- etr : scalar or array_like kc : scalar or array_like ts : scalar or array_like Surface temperature [K]. Returns ------- scalar or array_like Notes ----- 10...
def keyValueList(d, key=None): """ This function iterates over all the key-value pairs of a dictionary and returns a list of tuple (key, value) where the key contain only primitive value (i.e., no list or dict), e.g., string, number etc. d -- a dictionary to iterate through """ if not isinstance(d...
def retry_on_connection_error(exc: Exception): """Return True if there is an connection error exception.""" return isinstance(exc, (ConnectionError, TimeoutError, IOError))
def attr_list(x): """ parser for attribute lists on cli """ if ',' in x: return [y for y in x.split(',') if y.strip()] else: return [x]
def cleanup_favorite(favorite): """Given a dictionary of a favorite record, return a new dictionary for output as JSON.""" return str(favorite["post"])
def shorten_name(name): """Shortens a parkour room name.""" if name[0] == "*": return name.replace("#parkour", "", 1) return name.replace("-#parkour", "", 1)
def modevaltohex(mode_val): """ convert mode_val value that can be either xeh string or int to a hex string """ if isinstance(mode_val, int): return (hex(mode_val)[2:]).upper() if isinstance(mode_val, str): return mode_val return None
def _get_values(dct: dict) -> dict: """Remove description / value metadata from dictionary recursively.""" return { k: v["value"] if isinstance(v, dict) and "value" in v else _get_values(v) if isinstance(v, dict) else v for k, v in dct.items() }
def intersect(a1, b1, a2, b2): """finds the intersection of two lines""" x = (b1 - b2)/(a2 - a1) y = a1*x + b1 return x,y # ''' # returns list_tips, a list of spiral tips. Returns [] for no spiral tips. # contours_raw is the list of contour points for cond1, contours_edge is the list of # contour points wi...
def aod_type(dataID, stdoutFLG=True): """ input_parameters => dataID: label used to identify data set in the obsys_rc file => stdoutFLG: set to False, if calling directly from Python code purpose Identify AOD data type return value => aod_type_val: AOD data type """ # modis...
def number_to_name(number): """Take integer number as input (0-1-2-3-4) and returns string (rock-spock-paper-lizard-scissor) """ if number == 0: return "rock" elif number == 1: return "spock" elif number == 2: return "paper" elif number == 3: return "lizard" ...
def _is_gradient_task(task_id, num_tasks): """Returns True if this task should update the weights.""" if num_tasks < 3: return True return 0 <= task_id < 0.6 * num_tasks
def ip_to_int(a, b, c, d): """ Returns an integer For example 192.168.43.43 returns 3232246571 """ rv = (a * 16777216) + (b * 65536) + (c * 256) + (d) return rv
def black_invariant(text, chars=None): """Remove characters that may be changed when reformatting the text with black""" if chars is None: chars = [" ", "\t", "\n", ",", "'", '"', "(", ")", "\\"] for char in chars: text = text.replace(char, "") return text
def djangocms_misc_page_link(context, lookup, css_class='', link_text='', link_text_attr=''): """ link_text_attr is not working (yet) """ if not link_text_attr: link_text_attr = 'title' context.update({ 'lookup': lookup, 'css_class': css_class, 'link_text': link_text,...
def check_dependent_step_names(workflow): """ What it does: I. check if every calculation step copies from the correct parent calculation step (tag: copy_which_step) II. check if every calculation step has an array of correct additional depdendent steps (tag: additional_cal_dependence) I...
def execEmbCode(SCOPE, NAME, VAL, TEAL, codeStr): """ .cfgspc embedded code execution is done here, in a relatively confined space. The variables available to the code to be executed are: SCOPE, NAME, VAL, PARENT, TEAL The code string itself is expected to set a var named OUT """ ...
def format_value(number): """ Format the value with ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'). Defines the format of the value that will be shown on the /_health endpoint, this could be K, M, G ,etc :param number: The value to be use. :return: Formatted value. """ symbols = ('K', 'M', ...
def block_comments_begin_with_a_space(physical_line, line_number): """There should be a space after the # of block comments. There is already a check in pep8 that enforces this rule for inline comments. Okay: # this is a comment Okay: #!/usr/bin/python Okay: # this is a comment K002: #thi...
def get_intersection(features_list1: list, features_list2: list) -> list: """ Get intersection between two list of features as strings list :param features_list1: first list of features :param features_list2: second list of features :return: a list of string, composed of all elements both in feature...
def cycle_check(cycle_line): """find the cycle This is not efficient, but for a small sequence (50 ints) it works ok. Consider deque. Pop the first item from the front of the list. See if that item exists still in the list. If so, construct the loop list to return. """ while cycle_line: ...
def convert_title(original_title): """Remove underscores from string""" new_title = original_title.replace("_", " ").title() new_title = new_title.replace("Api", "API") return new_title
def _get_datapoint(datapoints, name, tags=None): """Find a specific datapoint by name and tags :param datapoints: a list of datapoints :type datapoints: [dict] :param name: the name of the required datapoint :type name: str :param tags: required tags by key and value :type tags: dict :r...
def ascii_identify(origin, *args, **kwargs): """Check whether given filename is ASCII.""" return (isinstance(args[0], str) and args[0].lower().split('.')[-1] in ['txt', 'dat'])
def max_sum_subarr(arr_a: list, arr_b: list) -> list: """ Time Complexity: O(m+n) Space Complexity: (n) """ set_b: set = set(arr_b) start, end, temp_start = -1, -1, 0 max_so_far, max_ending_here = 0, 0 for i, elem in enumerate(arr_a): if elem not in set_b: if max_end...
def validate_operator(operator_id, operator_config): """Method to validate operator_id recevd against defined operators in config.""" operator_ids = [op.id for op in operator_config] return True if operator_id in operator_ids else False
def sigmoid_derivative(x): """ The derivative of the Sigmoid function. This is the gradient of the Sigmoid curve. It indicates how confident we are about the existing weight. """ return x * (1 - x)
def split_list(l, n_part): """ :param list l: :param int n_part: :rtype: list[list] """ ret = list() for start_idx in range(n_part): ret.append(l[start_idx::n_part]) return ret
def dict_assign(obj, key, value): """Chainable dictionary assignment. Returns a copy. Parameters ---------- obj : dict A dictionary key : string Which attribute to set. May be a new attribute, or overwriting an existing one value A value of any type Returns ----...
def rectangle(f, a, b, n, height='left'): """Uses a rectangle method for integrating f. The height of each rectangle is computed either at the left end, middle or right end of each sub-interval""" h = float(b-a)/n if height == 'left': start = a elif height == 'mid': start = a + h...
def format_arguments(*args): """ Converts a list of arguments from the command line into a list of positional arguments and a dictionary of keyword arguments. Handled formats for keyword arguments are: * --argument=value * --argument value Args: *args (list): a list of arguments ...
def parse_bags(bag_restrictions: list) -> list: """Parse the list of raw bag restrictions given by the input file :param bag_restrictions: List of raw bag restrictions :return: Parsed bag restrictions """ parsed_restrictions = [] for line in bag_restrictions: parent_str, children_str = ...
def to_sql_list(xs): """stringify lists for SQL queries >>> to_sql_list([1, 2, 3]) == '1, 2, 3' """ def to_sql_literal(x): if isinstance(x, str): return "'{}'".format(x) return str(x) res = ", ".join(map(to_sql_literal, xs)) return res
def is_empty(string): """ Determines whether the provided string is empty or None or consists of only empty spaces :param string: :type str: :return: bool """ return string is None or len(string) == 0 or not bool(string.replace(' ', ''))
def get_source_path(path): """ If the path is for the .pyc, then removes the character 'c'. :param path: string :return: corrected path """ if path[-1] == 'c': return path[:-1] return path
def ascii_to_hex(__ascii): """ translates ASCII string into an array of hex ASCII codes """ return [hex(ord(c)).replace('0x', '') for c in __ascii]
def RTrim(text): """Strip spaces from the right of the text""" return str(text).rstrip()
def list_to_dict(list): """creates a dictionary out of a list assuming the list is written in alternating kwarg, arg,... the dictionary will be written as {kwarg:arg,..}. The first entry in the list is ommited, because that is usually a name""" dictio = {} for i in range(0,len(list),2):# ...
def s2s(s): """convert set to string""" return "{%s}" % ", ".join([str(x) for x in s])
def in_decimalhours(value): """ Returns decimal time in hours. e.g. 120 min = 2""" try: temp = int(value) except: raise ValueError('Error in "in_decimalhours" filter. Variable must be in convertable to int format.') output = value / 60 return output
def calc_permutation(m, mm, _accuracy): """ Evaluates the permutation expression """ value = 1 return value
def get_significant_parts(line): """ line is list of strings function returns list of nonempty elements""" wyn = [] for element in line: if element != '': wyn.append(element) return wyn # end get_significant_parts
def pad_sentences(sentences, padding_word="<PAD/>", maxlen=0): """ Pads all the sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. """ print('pad sentences...') if maxlen > 0: sequence_length = maxlen else: sequence_length...
def implies(cond1: bool, cond2: bool) -> bool: """Logical Implication, i.e. cond1 => cond2""" return (not cond1) or cond2
def reverse_number(num): """ Reverse a number. """ return int(str(num)[::-1])
def causal(effective_kernel_size: int): """Pre-padding such that output has no dependence on the future.""" return [effective_kernel_size - 1, 0]
def get_most_likely(emo, likelihood, most_likely_emotion): """Dado dos emociones conserva la de mayor probabilidad""" likelihood = likelihood.replace('Likelihood.', '') if likelihood == "VERY_LIKELY": return (emo,likelihood) if (likelihood == "LIKELY" and most_likely_emotion[1] != "VERY_LIKELY" ...
def sift(expr, keyfunc): """Sift the arguments of expr into a dictionary according to keyfunc. INPUT: expr may be an expression or iterable; if it is an expr then it is converted to a list of expr's args or [expr] if there are no args. OUTPUT: each element in expr is stored in a list keyed to the valu...
def _get_subtypes(sub_hier, subtypes=[]): """ A recursive function (I'm sorry) that converts lists all subtypes at the terminal nodes of a hierarchical branch. ... Parameters __________ sub_hier : Dict Hierarchical dictionary (a branch in the hierarchy) subtypes : List A l...
def hazard_id(value): """ >>> hazard_id('') () >>> hazard_id('-1') (-1,) >>> hazard_id('42') (42,) >>> hazard_id('42,3') (42, 3) >>> hazard_id('42,3,4') (42, 3, 4) >>> hazard_id('42:3') Traceback (most recent call last): ... ValueError: Invalid hazard_id '4...
def trim_float(value: float, places: int = 2) -> float: """Trim a float to N places. Args: value: float to trim places: decimal places to trim value to """ if isinstance(places, int): value = float(f"{value:.{places}f}") return value
def parse_line(line): """Takes a line formatted as three comma seperated integers. Returns three integers. """ n, p1, p2 = line.strip().split(',') return int(n), int(p1), int(p2)
def BuildReachableFileSet(entry_classes, reachability_tree, header_mapping): """Builds a set of reachable translated files from entry Java classes. Args: entry_classes: A comma separated list of Java entry classes. reachability_tree: A dict mapping translated files to their direct dependencies. ...
def convertToGenomicCoordinate(transcriptomic_coordinate,exon_list_genomic,transcript_id): """ """ exon_list_transcriptomic=[] for exon in exon_list_genomic: exon_start,exon_end=exon exon_length=exon_end-exon_start+1 if len(exon_list_transcriptomic)==0: exon_list_tran...
def rchop(text, end): """ Removes the end from the text if the text ends with it. """ if text.endswith(end): return text[:-len(end)] return text
def _to_tornado_pattern(transmute_path): """convert a transmute path to a tornado pattern. """ return ( transmute_path.replace("{", "(?P<") # .replace("}", ">[^\/]+)")) .replace("}", ">.*)") )
def write_the_species_tree(annotated_species_tree, output_file): """ this function writes the species tree to file args: annotated_species_tree : a string of annotated species tree in .newick format output_file : a file name to write to output: a file containing the anno...
def _qualify_optional_type(cpp_type): # type: (str) -> str """Qualify the type as optional.""" return 'boost::optional<%s>' % (cpp_type)
def _get_hidden_node_location(flattened_index, num_rows, num_columns): """Converts the flattened index of a hidden node to its index in the 3D array. Converts the index of a hidden node in the first convolution layer (flattened) into its location- row, column, and channel in the 3D activation map. The 3D activ...
def simple_hash(s: str) -> int: """A ridiculously simple hashing function""" basic_hash = ord(s[0]) return basic_hash % 10
def _ExtractTestsFromFilter(gtest_filter): """Returns the list of tests specified by the given filter. Returns: None if the device should be queried for the test list instead. """ # Empty means all tests, - means exclude filter. if not gtest_filter or '-' in gtest_filter: return None patterns = gt...
def _getIfromRGB(rgb): """Retrieve if from a specific layer color. Parameters ---------- rgb : Returns ------- """ red = rgb[2] green = rgb[1] blue = rgb[0] RGBint = (red << 16) + (green << 8) + blue return RGBint
def calc_weight(judge_i, pairing_i): """ Calculate the relative badness of this judge assignment We want small negative numbers to be preferred to large negative numbers """ return -1 * abs(judge_i - (-1 * pairing_i))
def truncate_stats(stat, threshold, name='Other'): """ Combines all entries (name, count) with a count below the threshold and appends a new entry :return: Truncated statistics with the last item being the addup of all truncated items. """ a, b = [], [] for s in stat: (a, b)[s[1] < thre...
def findLowestFolder(list1, list2): """ Sorts the folders in ascending order to increase organizational structure of the project """ tmp_string1 = str(list1) numbers = tmp_string1.split('_') tmp_string2 = str(list2) numbers2 = tmp_string2.split('_') if int(numbers[0]) > int(numbers2[0]...
def remove_duplicates(cascade_nodes,cascade_times): """ # Some tweets have more then one retweets from the same person # Keep only the first retweet of that person """ duplicates = set([x for x in cascade_nodes if cascade_nodes.count(x)>1]) for d in duplicates: to_remove = [v for v,b in ...
def getValues(params): """Extracts the attribute data Parameters: params (dict) Dictionary (node_attribute: value) Returns: (tuple) Tuple of the node attributes """ path = params.get("path") name = params.get("name") order = params.get("order") shape = params.get...
def truncate(content, length=100, suffix='...'): """ Smart string truncation """ if len(content) <= length: return content else: return content[:length].rsplit(' ', 1)[0] + suffix
def load_ldap_settings(config): """ Load all the ldap configuration settings into a dict LDAP configuration settings contain an ldap_ prefix. Args: config (dict): the global config Returns: (dict) All the ldap_ settings """ ldap_config = {} for key, value in config.items()...