content
stringlengths
42
6.51k
def extend_padding(ls_of_ls, padding=''): """ Takes in a lists of lists, returns a new list of lists where each list is padded up to the length of the longest list by [padding] (defaults to the empty string) """ maxlen = max(map(len, ls_of_ls)) newls = [] for ls in ls_of_ls: if l...
def haxelib_homepage_url(name, baseurl='https://lib.haxe.org/p/'): """ Return an haxelib package homepage URL given a name and a base registry web interface URL. For example: >>> assert haxelib_homepage_url('format') == u'https://lib.haxe.org/p/format' """ baseurl = baseurl.rstrip('/') ...
def get_pattern_precise(guess: str, solution: str): """generates the patterns for a guess""" hint = "" for index, letter in enumerate(guess): if not letter in solution: hint += "b" else: if letter == solution[index]: hint += "g" else: ...
def format_settings(file_rows): """ Takes a list of settings (as written in config files) and formats it to a dictionary. Returns a dictionary with all settings as keys. """ SETTING_PART_LENGTH = 2 settings = {} for row in file_rows: row = row.strip("\n") parts = row.split("=", 1) if len(parts) == S...
def has_wiki_desc(resp: dict) -> bool: """ Check if a POI response contains a Wikipedia description. """ return any(b["type"] == "description" and b["source"] == "wikipedia" for b in resp["blocks"])
def reward_clipping(rew): """ Sets positive rewards to +1 and negative rewards to -1. Args: rew: A scalar reward signal. Returns: +1. if the scalar is positive, -1. if is negative and 0 otherwise. """ if rew > 0: return 1. if rew < 0: return -1. return 0...
def find_output_processes(process_id, connections): """ Finds all the processes that this process outputs to """ me = connections[process_id] outputs_to = [] for proc_id in connections: if proc_id == process_id: # Don't look at our own process continue pro...
def snake(s): """Convert from title or camelCase to snake_case.""" if len(s) < 2: return s.lower() out = s[0].lower() for c in s[1:]: if c.isupper(): out += "_" c = c.lower() out += c return out
def put_items_to_boxes(items, weights, n, cutoff): """Put seqs into n boxes, where stop to put more items when sum of weight in a box is greater than or equal to a cutoff items --- a list of strings weights --- item weights n --- number of boxes cutoff --- sum of weight cutoff to stop putting items ...
def clean(text): """cleans text string by removing (date), - company""" # re.sub(r'\s*\(\d{4}\)\s*', '', "text") return text
def __create_gh_repo_url(account: str, repo: str) -> str: """ Given an account name and a repo name, returns a cloneable gh repo url. """ return 'https://github.com/' + account + '/' + repo + '.git'
def one_space(value): """"Removes empty spaces, tabs and new lines from a string and adds a space between words when necessary. Example: >>> from phanterpwa.tools import one_space >>> one_space(" My long \r\n text. \tTabulation, spaces, spaces. ") 'My long text. Ta...
def splitChunkAndSignature(chunk): """Simple wrapper method to separate the signature from the rest of the chunk. Arguments: chunk {bytes} -- Everything inside the message field of an IOTA tx. Returns: bytes -- Everything except the trailing 64 bytes. bytes -- 64 bytes long signature. """ signature = ch...
def ssn_checksum(number): """ Calculate the checksum for the romanian SSN (CNP). """ weights = (2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9) check = sum(w * int(n) for w, n in zip(weights, number)) % 11 return 1 if check == 10 else check
def limits(centre, out, valid): """ Calculate matrix borders with limits """ bottom = max(valid[0], centre-out) top = min(valid[1], centre+out) return bottom, top
def int_2_bool(value): """Converts an integer, eg. 0, 1, 11, 123 to boolean Args: value (int) Returns: False for value: 0 True otherwise """ if isinstance(value, int): return (bool(value)) else: return False
def len_str_list(lis): """returns sum of lengths of strings in list()""" res = 0 for x in lis: res += len(x) return res
def fib_nr(n): """Fibonacci: fib(n) = fib(n-1) + fib(n-2) se n > 1 fib(n) = 1 se n <= 1 """ # seq = [1,1] #calculando os outros for i in range(2, n + 1): seq.append(seq[i-1] + seq[i-2]) return seq[n]
def is_nan_numeric(value) -> bool: """ Check for nan and inf """ try: value = str(value) value = float(value) except Exception: return False try: if isinstance(value, float): a = int(value) # noqa isnan = False except Exception: ...
def get_length(alt_len, ref_len, category, pos, end, svtype=None, svlen=None): """Return the length of a variant Args: alt_len(int) ref_len(int) category(str) svtype(str) svlen(int) """ # -1 would indicate uncertain length length = -1 if category in ('snv...
def deduplicate_dicts(l: list) -> list: """ Removes duplicate dicts from a list of dicts, preserving order """ seen = set() new_l = [] for d in l: t = tuple(d.items()) if t not in seen: seen.add(t) new_l.append(d) return new_l
def is_permutation_palindrome(string): """Returns True if a permutation is a variation of a palindrome or False otherwise""" if type(string) != str: raise TypeError( "The argument for is_permutation_palindrome must be of type string.") tracker = set() for char in string: i...
def spd_units_string(units, units_only=False): """ Return string describing particle data units for labels Input: units: str String describing units Returns: String containing full units string """ out = ['', 'Unknown', ''] units = units.lower() if units ==...
def length_palindrome(full_string, center, odd=True): """ Helper function that returns the length of the palindrome centered at position center in full_string. If the palidrome has even length, set odd=False, otherwise set odd=True. """ # We will increase the palindrom simultaneously in both dir...
def refresh_token_as_str(refresh_token): """Convert refresh token settings (set/not set) into string.""" return "set" if refresh_token else "not set"
def bits_to_int(bits: list, base: int = 2) -> int: """Converts a list of "bits" to an integer""" return int("".join(bits), base)
def sort_list(lst, index2sorton, type='asc'): """ """ if type=='asc': return sorted(lst, key=lambda x: x[index2sorton]) elif type=='des': return sorted(lst, key=lambda x: x[index2sorton], reverse=True)
def prt_bytes(bytes, human_flag): """ convert a number > 1024 to printable format, either in 4 char -h format as with ls -lh or return as 12 char right justified string """ if human_flag: suffix = '' mods = list('KMGTPEZY') temp = float(bytes) if temp > 0: ...
def flatten(items): """Convert a sequence of sequences to a single flat sequence. Works on dictionaries, tuples, lists. """ result = [] for item in items: if isinstance(item, list): result += flatten(item) else: result.append(item) return result
def get_input_words(word_counts, reserved_tokens, max_token_length): """Filters out words that are longer than max_token_length or are reserved. Args: word_counts: list of (string, int) tuples reserved_tokens: list of strings max_token_length: int, maximum length of a token Returns: ...
def extend_sequence(sequence, item): """ Simply add a new item to the given sequence. Simple version of extend_distribution_sequence, since not using distributions here makes the equalization of distributions in sequence irrelevant. """ sequence.append(item) return sequence
def calculate_satoshis(my_list_of_outputs): """Calculate satoshis.""" result = 0 for output in my_list_of_outputs: result += output.satoshis return result
def checkValues_coordinate0(coordinate0, reference_point): """Function that check the range of the input coordinates to be rigth""" # AP if 90 > coordinate0[0] > -90: pass # Entry in correct range else: raise Exception( "Coordinate AP ({}) out of range for lambda, should be...
def environment_tag_targets_for_instances(ilist): """ Generate List of possible targets ordered by environment key. """ env_nodes = {} for i in ilist: if i.tags is None: continue for tag in i.tags: if tag['Key'] == 'environment' or tag['Key'] == 'Environment'...
def decode_textfield_quoted_printable(content): """ Decodes the contents for CIF textfield from quoted-printable encoding. :param content: a string with contents :return: decoded string """ import quopri return quopri.decodestring(content)
def convert_single_value_to_tuple(value): """This function converts a single value of nearly any type into a tuple. .. versionchanged:: 3.2.0 The function has been aesthetically updated to be more PEP8 compliant. .. versionadded:: 2.3.0 :param value: The value to convert into a tuple """ ...
def vowels(value): """Count the number of vowels in a string.""" return sum(1 for char in value.lower() if char in "aeiou")
def get_direction(start, finish): """Return left right up or down, dependent on dir between start finish (x,y) coordinate pairs""" if start[1] > finish[1]: dir = "up" elif start[1] < finish[1]: dir = "down" elif start[0] > finish[0]: dir = "left" elif start[0] < finish[0]: ...
def make_node_pairs_along_route(route): """Converts a list of nodes into a list of tuples for indexing edges along a route. """ return list(zip(route[:-1], route[1:]))
def parse_auth_response(text): """Parse received auth response.""" response_data = {} for line in text.split("\n"): if not line: continue key, _, val = line.partition("=") response_data[key] = val return response_data
def _IsValidComposerUpgrade(cur_version, candidate_version): """Validates that only MINOR and PATCH-level version increments are attempted. (For Composer upgrades) Checks that major-level remains the same, minor-level ramains same or higher, and patch-level is same or higher (if it's the only change) Args:...
def _test_jpeg(h): """JPEG data with JFIF or Exif markers; and raw JPEG""" if h[6:10] in (b'JFIF', b'Exif'): return 'jpeg' elif h[:4] == b'\xff\xd8\xff\xdb': return 'jpeg'
def db2dbm(quality): """ Converts the Radio (Received) Signal Strength Indicator (in db) to a dBm value. Please see http://stackoverflow.com/a/15798024/1013960 """ dbm = int((quality / 2) - 100) return min(max(dbm, -100), -50)
def recurse_while(predicate, f, *args): """ Accumulate value by executing recursively function `f`. The function `f` is executed with starting arguments. While the predicate for the result is true, the result is fed into function `f`. If predicate is never true then starting arguments are returned...
def ppm_to_freq(ppm, water_hz=0.0, water_ppm=4.7, hz_per_ppm=127.680): """ Convert an array from chemical shift to Hz """ return water_hz + (ppm - water_ppm) * hz_per_ppm
def api_full_name(api_name, api_version, organization_name): """Canonical full name for an API; used to generate output directories and package name""" if api_version: return '-'.join([organization_name, api_name, api_version]) else: return '-'.join([organization_name, api_name])
def filter_interface_conf(c): """Determine if an interface configuration string is relevant.""" c = c.strip() if c.startswith("!"): return False if c.startswith("version "): return False if c.startswith("interface"): return False if not c: return False return ...
def colorscale_to_colors(colorscale): """ Converts a colorscale into a list of colors """ color_list = [] for color in colorscale: color_list.append(color[1]) return color_list
def _get_marker_style(obs_stat, p, one_sided_lower): """Returns matplotlib marker style as fmt string""" if obs_stat < p[0] or obs_stat > p[1]: # red circle fmt = 'ro' else: # green square fmt = 'gs' if one_sided_lower: if obs_stat < p[0]: fmt = 'ro' ...
def ease_out_quad(n: float) -> float: """A quadratic tween function that begins fast and then decelerates.""" return -n * (n - 2)
def cap_digit(digit): """ This function will ensure that entered digit doesnt go above 9 to represent all single digits. Also due to Exixe SPI technical details the 10th slot in the bytes array controls the 0 digit. Here is where we will convert the 0 digit to 10 to represent this correctly. More in...
def seq3(seq): """Turn a one letter code protein sequence into one with three letter codes. The single input argument 'seq' should be a protein sequence using single letter codes, either as a python string or as a Seq or MutableSeq object. This function returns the amino acid sequence as a string usin...
def is_numeric(x): """Returns whether the given string can be interpreted as a number.""" try: float(x) return True except: return False
def _maxdiff(xlist, ylist): """Maximum of absolute value of difference between values in two lists. """ return(max(abs(x-y) for x, y in zip(xlist, ylist)))
def parents(digraph, nodes): """ """ nodes = set(nodes) parents = set() for parent, children in digraph.items(): if nodes & set(children): parents.add(parent) return parents
def uniqlist(l): """ return unique elements in a list (as list). """ result = [] for i in l: if i not in result: result.append(i) return result
def toNumber(s): """Tries to convert string 's' into a number.""" try: return int(s) except ValueError: return float(s)
def get_digit(unit: int, number: int) -> int: """ Finds the digit on the given unit """ # Gets the number to have the desired # digit on the last unit while unit > 0: number //= 10 unit -= 1 return number % 10
def clip_bedfile_name(bedfile): """ clip bed file name for table/plotting purposes; assumes file naming system matches that of Pipeliner """ toolused = bedfile.split("/")[-3] sample = bedfile.split("/")[-2] return( toolused, sample )
def get_heading_level(heading): """Returns the level of a given Markdown heading Arguments: heading -- Markdown title """ i = 0 while( i < len(heading) and heading[i] == '#' ): i += 1 return i
def generate_master(playlists): """Generate master playlist. Playlists arg should be a map {name: url}. Little validation or encoding is done - please try to keep the names valid without escaping. """ lines = ["#EXTM3U"] for name, url in playlists.items(): lines += [ # We name each variant with a VIDEO rendi...
def get_digits(value: float) -> int: """ Get number of digits after decimal point. """ value_str: str = str(value) if "e-" in value_str: _, buf = value_str.split("e-") return int(buf) elif "." in value_str: _, buf = value_str.split(".") return len(buf) else: ...
def grep(pattern, filename): """Very simple grep that returns the first matching line in a file. String matching only, does not do REs as currently implemented. """ try: # for line in file # if line matches pattern: # return line return next((L for L in open(filename) ...
def binary_search_recur(arr, low, high, num): """ recursive variant of binary search """ if low > high: # error case return -1 mid = (low + high) // 2 if num < arr[mid]: return binary_search_recur(arr, low, mid - 1, num) if num > arr[mid]: return binary_search_recur(...
def check_bibtex_entry(entry, fix = False): """ Check whether an entry is suitable for the database. Returns None if all is ok, else returns a user-readable string describing the error. If fix is set to true then will 'fix' any problems by replacing errors with dummy values. This is only useful during testing and...
def dot_notation(dict_like, dot_spec): """Return the value corresponding to the dot_spec from a dict_like object :param dict_like: dictionary, JSON, etc. :param dot_spec: a dot notation (e.g. a1.b1.c1.d1 => a1["b1"]["c1"]["d1"]) :return: the value referenced by the dot_spec """ attrs = dot_spec....
def parse_anno(text): """Convert text with layer annotation to data structure""" return eval(text) if text else None
def default_pretransform(sample, values): """Returns the image sample without transforming it at all Args: sample: Loaded image data values: Tuple such that the 1th arguement is the target (defined by default) Returns: var: The loaded sample image int: Value representing the...
def predict_four(student): """ Predicts four year retention of a student >>> predict_four({ ... 'hs_grade':7, ... 'sat_verbal':600, ... 'sat_math':600, ... 'gender':1, ... 'white':2, ... 'native_american':1, ... 'black':1, ... 'mexican_american':1, ... }) 0.6618 """ return...
def _contains_edge(edges_set, vertex1, vertex2): """ Check if the container has an edge between the given vertices. The edge can be (vertex1, vertex2) or (vertex2, vertex1). """ return (vertex1, vertex2) in edges_set or (vertex2, vertex1) in edges_set
def parse_hpo_disease(hpo_line): """Parse hpo disease line Args: hpo_line(str) """ hpo_line = hpo_line.rstrip().split('\t') hpo_info = {} disease = hpo_line[0].split(':') hpo_info['source'] = disease[0] hpo_info['disease_nr'] = int(disease[1]) hpo_info['hgnc...
def parse_indexes(x): """parse a string into a set of indexes""" # verify the quality of the input ok = [str(_) for _ in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ",", "-"]] for d in x: if d not in ok: raise Exception("unacceptable index string") result = set() for xpart in x.split(",...
def average(data): """ Calculate the average of values of the data. Args: data (list): values. Returns the average of values of the data. """ return 1.0*sum(data)/len(data)
def wheel(wheel_pos): """Color wheel to allow for cycling through the rainbow of RGB colors.""" wheel_pos = wheel_pos % 256 if wheel_pos < 85: return 255 - wheel_pos * 3, 0, wheel_pos * 3 elif wheel_pos < 170: wheel_pos -= 85 return 0, wheel_pos * 3, 255 - wheel_pos * 3 else:...
def get_fsubmission_obj(parent, obj_id): """ Inverse of id() function. But only works if the object is not garbage collected""" print("get_fsubmission_obj parent: ", parent) if parent: return parent.find_obj_by_id(parent, obj_id) print("cannot find obj")
def letters_in(string): """Return sorted list of letters in given string.""" return sorted( char for char in string.lower() if char.isalpha() )
def shift_backward(text, spaces): """ Shifts the given string or list the given number of spaces backward :param str text: Text to shift :param int spaces: Number of spaces to shift the text backwards by :return: Backward-shifted string :rtype: str """ output = text[spaces::] if type(...
def fatorial(numero, show=False): """ Funcao que recebe um numero e devolve seu fatorial. :param numero: numero a se calcular. :param show: (opcional) mostrar o calculo. :return: resultado do calculo fatorial. """ fatorial = 1 for counter in range(numero, 0, -1): fatorial *= coun...
def filter_nodes(nodes_list, ids=None, subtree=True): """Filters the contents of a nodes_list. If any of the nodes is in the ids list, the rest of nodes are removed. If none is in the ids list we include or exclude the nodes depending on the subtree flag. """ if not nodes_list: return...
def mimebundle_to_html(bundle): """ Converts a MIME bundle into HTML. """ if isinstance(bundle, tuple): data, metadata = bundle else: data = bundle html = data.get('text/html', '') if 'application/javascript' in data: js = data['application/javascript'] html +...
def epiweek_to_month(ew): """ Convert an epiweek to a month. """ return (((ew - 40) + 52) % 52) // 4 + 1
def _get_table_to_primary_key_columns( table_to_column_metadata, table_to_explicit_primary_key_columns, primary_key_selector ): """Return the set of primary key columns for each table.""" table_to_primary_key_columns = {} for table_name in table_to_column_metadata: if table_name in table_to_expl...
def _null_to_empty(val): """Convert to empty string if the value is currently null.""" if not val: return "" return val
def in_cksum_add(s, buf): """in_cksum_add(cksum, buf) -> cksum Return accumulated Internet checksum. """ nleft = len(buf) i = 0 while nleft > 1: s += ord(buf[i]) * 256 + ord(buf[i+1]) i += 2 nleft -= 2 if nleft: s += ord(buf[i]) * 256 return s
def _get_c_string(data, position): """Decode a BSON 'C' string to python unicode string.""" end = data.index(b"\x00", position) return data[position:end].decode('utf8'), end + 1
def _parse_line_remove_comment(line): """Parses line from config, removes comments and trailing spaces. Lines starting with "#" are skipped entirely. Lines with comments after the parameter retain their parameter. Parameters -------------- line : str Returns -------------- line :...
def index_of_opening_parenthesis(words, start, left_enc ='(', right_enc =')'): """Returns index of the opening parenthesis of the parenthesis indicated by start.""" num_opened = -1 i = start-1 while i >= 0: if words[i] == left_enc: num_opened += 1 elif words[i] == right_enc: ...
def unquote(string): """stripped down implementation of urllib.parse unquote_to_bytes""" if not string: return b'' if isinstance(string, str): string = string.encode('utf-8') # split into substrings on each escape character bits = string.split(b'%') if len(bits) == 1: ...
def gateway_options(gateway_options): """Deploy template apicast staging gateway.""" gateway_options["path_routing"] = True return gateway_options
def php_str_noquotes(data): """ Convert string to chr(xx).chr(xx) for use in php """ encoded = "" for char in data: encoded += "chr({0}).".format(ord(char)) return encoded[:-1]
def do(func, x): """ Runs ``func`` on ``x``, returns ``x`` Because the results of ``func`` are not returned, only the side effects of ``func`` are relevant. Logging functions can be made by composing ``do`` with a storage function like ``list.append`` or ``file.write`` >>> from toolz import c...
def get_start_timestamp(start_time): """ get start timestamp to use in datasetname It removes the hyphens and colons from the timestamp :param start_time: :return: """ start_time = start_time.replace("-","") start_time = start_time.replace(":","") return start_time
def defined_or_defaut_dir(default, directory): """ if given a directory it will return that directory, otherwise it returns the default """ if directory: return directory else: return default
def mdce(aa, bb, __verbose = False): """ Algoritmo euclideano estendido, utilizado para calcular os valores das constantes alfa e beta que satifazem equacoes da forma a * alfa + b * beta = mdc(a,b) r | q | x | y a | * | 1 | 0 b | * | 0 ...
def remove_trailing_whitespace(line): """Removes trailing whitespace, but preserves the newline if present. """ if line.endswith("\n"): return "{}\n".format(remove_trailing_whitespace(line[:-1])) return line.rstrip()
def merge_dict(data, *override): """ Merges any number of dictionaries together, and returns a single dictionary """ result = {} for current_dict in (data,) + override: result.update(current_dict) return result
def compare_dictionaries(dict_1, dict_2, dict_1_name, dict_2_name, path=""): """Compare two dictionaries recursively to find non mathcing elements Args: dict_1: dictionary 1 dict_2: dictionary 2 Returns: """ err = '' key_err = '' value_err = '' old_path = path for ...
def get_room_media(roomid,rooms_media): """Get all room media.""" media = [] for i in rooms_media: if i[0] == roomid: media.append(i[1]) return media
def makeVector(dim, initValue): """ Return a list of dim copies of initValue """ return [initValue]*dim
def _unflatten(mapping): """Converts a flat tuple => object mapping to hierarchical one""" result = {} for path, value in mapping.items(): parents, leaf = path[:-1], path[-1] # create the hierarchy until we reach the leaf value temp = result for parent in parents: ...