content
stringlengths
42
6.51k
def flat_list(*alist): """ Flat a tuple, list, single value or list of list to flat list e.g. >>> flat_list(1,2,3) [1, 2, 3] >>> flat_list(1) [1] >>> flat_list([1,2,3]) [1, 2, 3] >>> flat_list([None]) [] """ a = [] for x in alist: if x is None: ...
def _has_variable_name(s): """ Variable name before [ @param s: string """ return s.find('[') > 0
def correct_sentence(text: str) -> str: """ returns a corrected sentence which starts with a capital letter and ends with a dot. """ # your code here return text[:1].upper() + text[1:] + '.' if not text.endswith('.') else text[:1].upper() + text[1:]
def compute_log_level(verbosity: int) -> int: """Matches chosen verbosity with default log levels from the logging module. Each verbosity increase (i.e. adding `-v` flag) should decrease a logging level by some value which is below called as 'verbosity_step'. Moreover, start log level, and minimum log ...
def merge_keywords(x,y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z
def path_join(*components): """Join two or more pathname COMPONENTS, inserting '/' as needed. Empty component are skipped.""" return '/'.join(filter(None, components))
def factorial_zeroes(n): """Consider a factorial like 19!: 19! = 1*2* 3*4* 5*6*7*8*9* 10* 11* 12* 13*14*15* 16* 17*18*19 A trailing zero is created with multiples of 10 and multiples of 10 are created with pairs of 5-multiples and 2-multiples. Therefore, to count the number of zeros, we only ...
def get_top_package_from_qualified_path(full_module_name: str) -> str: """Gets top-level package name from qualified (dotted) module name.""" return full_module_name.split(".")[0]
def calc_fdr(true_pos, false_pos): """ function to calculate false discovery rate Args: true_pos: Number of true positives false_pos: Number of false positives Returns: None """ try: fdr = false_pos / float(true_pos + false_pos) return round(fdr, 3) except BaseException: return N...
def task_status(task_row): """ Determine whether a task has been finished, started or created """ if task_row['exec_time']: return 'Completed' elif task_row['start_time']: return 'Run' else: return 'In Queue'
def get_job_details(job_id): """ Get Job details :param job_id: :return: """ job = {"job_id": job_id, "details": "Details go here"} return job
def line2extension( header, line ): """ Converts wavelength string into an extension number. Returns -1 if the line could not be found or several lines where found. Parameters ---------- header : astropy.io.fits.header.Header Primary header of the FITS file line : str Li...
def get_vm_lease_data(data): """ Simple function to transform instance database proxy object into an externally consumable dictionary. :param data: database row object """ return {'instance_uuid': data['instance_uuid'], 'tenant_uuid': data['tenant_uuid'], 'expiry': data['...
def stretch(low, high, fraction): """Stretch out interval by the given fraction.""" delta = abs(high - low)*fraction return (low - delta, high + delta)
def which_read(flag): """(int) -> str Returns read number based on flag. Test cases: >>> which_read(83) 'R1' >>> which_read(131) 'R2' >>> which_read(177) 'R2' """ read1 = [99, 83, 67, 115, 81, 97, 65, 113] read2 = [147, 163, 131, 179, 161, 145, 129, 177] if flag in ...
def is_likely_human(response): """ From the email validation response, determine whether a given email is valid by combining the various signals in an opinionated way to return a boolean. This can be tweaked to be more/less aggressive. An individual response looks like this: {'address': '...
def week_day_on_first_auroran(dek_year: int) -> int: """Returns the Gregorian week day for the first Auroran of a given year Args: dek_year (int): Year. Return: int: The week day. Example: 1 = Sunday; 2 = Monday; 3 = Tuesday ... 7 = Saturday. """ week_day = ( ( ...
def rotate(v, n=1): """Rotates the elements of a sequence by (n) places. Returns a new list. """ n %= len(v) return v[n:] + v[:n]
def build_file_unique_id(doc): """Build file unique identifier.""" doc['unique_id'] = '{0}_{1}'.format(doc['bucket_id'], doc['file_id']) return doc
def recursive_thue_morse(n): """The recursive definition of the Thue-Morse sequence. The first few terms of the Thue-Morse sequence are: 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 . . .""" if n == 0: return 0 if n % 2 == 0: return recursive_thue_morse(n / 2) if n % 2 == 1: return 1 - r...
def parse_wall_segment_line1(line): """ helper parse_sfo_segment """ d = {} ix, x = line.split('segment')[1].split(' K,L =') d['segment_number'] = int(float((ix))) kl0, kl1 = x.split('to') k0, l0 = kl0.split(',') d['K_beg'], d['L_beg'] = int(k0), int(l0) k1, l1 = kl1.split(',') ...
def capped(value, minimum=None, maximum=None, key=None, none_ok=False): """ Args: value: Value to cap minimum: If specified, value should not be lower than this minimum maximum: If specified, value should not be higher than this maximum key (str | None): Text identifying 'value' ...
def parse_symbols(truth): """Returns the unique tokens of the groundtrurh. Args: truth(string) : groundtruth Returns: unique_symbols(set): unique_symbols """ unique_symbols = set(truth.split()) return unique_symbols
def getKmers(k, bases): """Generate k-mers of size k""" import itertools kmers = [''.join(p) for p in itertools.product(bases, repeat=k)] return kmers
def fmt_percent(value: float, edge_cases: bool = True) -> str: """Format a ratio as a percentage. Args: edge_cases: Check for edge cases? value: The ratio. Returns: The percentage with 1 point precision. """ if not (1.0 >= value >= 0.0): raise ValueError(f"Value '{v...
def filter_deployments_using_secret(secret_names, deployments_as_yaml): """Return a dictionary of deployments using the secret we are filtering on.""" deployments_using_secrets = {} for deployment in deployments_as_yaml: found_secret = False containers = deployment['spec']['template']['...
def sum_of_lists(lists): """Aggregates list of numeric lists by summing.""" if len(lists) == 1: return lists[0] # Preserve datatype size = len(lists[0]) init_val = type(lists[0][0])(0.0) total = [init_val] * size for ll in lists: for i in range(size): total[i] +=...
def get_difference(list1, list2): """Takes two lists and returns list filled by elements of list1 that are absent at list2. Duplicates are removed too""" #res = s1 = set(list1) s2 = set(list2) return list(s1- s2)
def clean_walkscore(walkscore_details: dict) -> dict: """Extracts the desired walkscore information for API return. Args: walkscore_details (dict): Collected walkscore payload Returns: dict: Key items desired from walkscore """ return { "walkscore": walkscore_details.get("w...
def fizz_buzz(input_number, fizz=3, buzz=5): """Fizz Buzz function. input_number: number being tested. fizz: multiple should be replaced by fizz. Default 3. buzz: multiple should be replaced by buzz. Default 5. """ output = "" if input_number % fizz == 0: output += "Fizz" if inp...
def slidingWindow(sequence,winSize,step): """Returns a generator that will iterate through the defined chunks of input sequence. Input sequence must be iterable. From scipher.wordpress.com""" # Verify the inputs try: it = iter(sequence) except TypeError: raise Exception("**ERROR** sequence must be iterable.")...
def trim(text, tabwidth=4): """ Trim text of common, leading whitespace. Based on the trim algorithm of PEP 257: http://www.python.org/dev/peps/pep-0257/ """ if not text: return '' lines = text.expandtabs(tabwidth).splitlines() maxindent = len(text) indent = maxindent ...
def first_differences(signal): """The mean of the absolute values of the first differences of the raw signal""" # build the first differences list first_diff = [] for i in range(0,len(signal)-1): first_diff.append(abs(signal[i+1]-signal[i])) fd_sum = sum(first_diff) delta = float(fd_sum)/(len(signal)-1) retur...
def is_camel(text): """ Check if a string is in either upper or lower camel case format :param text: String to check :return: Whether string is in any camel case format """ if " " in text: return False return "_" not in text and not text.isupper() and not text.islower()
def squared_error(x, rho, x_obs): """ Proximal operator for squared error (l2 or Fro. norm) squared_error(x_obs) Parameters ---------- x_obs : array_like Observed array or matrix that you want to stay close to """ return (x + x_obs / rho) / (1. + 1. / rho)
def xy_to_upvp(xy): """Convert xy to u'v' Args: xy ([float, float]): x, y input values Returns: .[float, float] """ x, y = xy up = 4 * x / (-2 * x + 12 * y + 3) vp = 9 * y / (-2 * x + 12 * y + 3) return [up, vp]
def covert_dic(dicts: dict) -> dict: """ Convert all the values in a dictionary to str and replace char, for example: <class 'torch.Tensor'>(unknow type) to torch.Tensor(str type). Args: dicts (`dict`): The dictionary to convert. Returns: (`dict`) The conve...
def file_ending(filename): """Extract file ending.""" return filename.split(".")[-1]
def simple_validator(passport): """Checks if a passport is valid (quick and dirty and wrong)""" if len(passport) == 8: return True if len(passport) == 7 and "cid" not in passport: return True return False
def printPath(path): """Assumes path is a list of nodes""" result = '' for i in range(len(path)): result = result + str(path[i]) if i != len(path) - 1: result = result + '->' return result
def get_author(generator): """ lecture de l inofrmation """ try: doc = next(generator) except Exception as e: doc = None print("Excp:" + str(e)) return doc
def hold_timer(suc_bool, ep_timesteps, real_t_per_ts, min_time, start_time): """ Get result of a timer to decide whether a success reward criteria has been met for long enough """ if ep_timesteps <= 1: start_time = None # acts as a reset done_success = False if suc_bool: if start_time ...
def is_code_cell(cell): """Returns whether a cell is a code cell Args: cell (``nbformat.NotebookNode``): the cell in question Returns: ``bool``: whether a cell is a code cell """ return cell["cell_type"] == "code"
def get_shortest_topmost_directories(dirs): """Return the shortest topmost directories from the dirs list. Args: dirs: A list of directories Returns: The shortest list of parent directories s, such that every directory d in dirs can be reached from one (and only one) directory in s...
def kickOnBetween(i, i_set, j, j_set): """@ kick on between Turns on debugging parameters when the specific indices i and j meet the condition that i_set <= i and j <= j_set, and turns these debugging parameters off when i < i_set and/or j > j_set. """ flag_on = False if ...
def smallest(a, b): """ This function returns the smallest of the numbers (but it does checks for None). Input: a: int, first number; b: int, second number. Output: smallest: int, the smallest number of the passed numbers (the non-None number, if one of ...
def indent(text): """Indent all but the first line of the given text so it won't contain an FTP return code.""" text = text.replace("\r\n","\n") if text.endswith("\n"): text = text[:-1] return text.replace("\n", "\r\n ")
def parse_char(char, invert=False): """Return symbols depending on the binary input Keyword arguments: char -- binary integer streamed into the function invert -- boolean to invert returned symbols """ if invert == False: if char == 0: return '.' elif char == 1...
def UNIX_text(text): """Convert line breaks from DOS/Windows or Macintosh to UNIX convention. DOS/Windows: '\n\r', Macinosh: '\r':, UNIX: '\n'""" if not "\r" in text: return text # already in UNIX format text = text.replace("\n\r","\n") # was DOS to UNIX text = text.replace("\r\n","\n") # was ? to U...
def format_name(rank_name): """Reformats a name to avoid reserved characters.""" rep_tups = ((' ', '_'), (':', '-'), (';', ','), ('|', '_')) for rep_tup in rep_tups: orig_char, rep_char = rep_tup rank_name = rank_name.replace(orig_char, rep_char) return rank_name
def atleast_ndim(x, ndim): """Reshapes a tensor so that it has at least n dimensions.""" if x is None: return None return x.view(list(x.shape) + [1] * (ndim - x.ndim))
def from_bcd(data: bytes) -> int: """ make a bcd encoded bytestring into an integer Example: b"\x30" should be 30 """ chars = data.hex() return int(chars)
def add_matrices2D(mat1, mat2): """add_matrices2D: adds two matrices element-wise Args: mat1: First matrix to sum mat2: Second matrix to sum """ if len(mat1[0]) == len(mat2[0]): result = [[mat1[x][y] + mat2[x][y] for y in range(len(mat1[0]))] for x in range(le...
def sum_of_powers(numbers, power): """ Sums each number raised to power Ex: sum_of_powers([2, 3, 4], 2) = 2^2 + 3^2 + 4^2 = 29 """ return sum(pow(number, power) for number in numbers)
def user_model(email): """Return a user model""" return { 'email': email, }
def currency2float(currency): """convert currency to float >>> currency2float("10.08") 10.08 >>> currency2float("12,313.66") 12313.66 >>> currency2float("102.5M") 102500000 """ if currency == '': return '' if currency[-1:] == "M": currency = currency[:-1] ...
def dict_to_capabilities(caps_dict): """Convert a dictionary into a string with the capabilities syntax.""" return ','.join(["%s:%s" % (key, value) for key, value in caps_dict.items() if value is not None])
def sessions(request): """ Cookies prepeocessor """ context = {} return context
def string_diff_column(str1, str2): """ >>> string_diff_column("ab1", "ab2") 3 >>> string_diff_column("ab1c3e", "ab2c4e") 3 >>> string_diff_column("abc", "abcd") 3 >>> string_diff_column("abcd", "abc") 3 >>> string_diff_column("a", "") 1 >>> string_diff_column("", "a") ...
def pos(needle, haystack, start=1): """returns the character position of one string, needle, in another, haystack, or returns 0 if the string needle is not found or is a null string. By default the search starts at the first character of haystack (start has the value 1). You can override this by spe...
def try_or_none(func, exceptions): """Helper that tries to execute the function If one of the ``exceptions`` is raised then return None """ try: return func() except exceptions: return None
def find_public_atrs(obj): """Find the public attributes of an object. private attributes have a leading underscore ("_") """ atrs = dir(obj) return [atr for atr in atrs if not atr.startswith('_')]
def parse_ptsset(word_list): """ Parses a PtstoSet from the log """ # format { val val val } ret = set() assert word_list[0] == "{" and word_list[-1] == "}" for word in word_list[1:-1]: ret.add(int(word)) return ret
def fix2range(vals, minval, maxval): """ A helper function that sets the value of the array or number `vals` to fall within the range `minval` <= `vals` <= `maxval`. Values of `vals` that are greater than `maxval` are set to `maxval` (and similar for `minval`). Parameters ---------- va...
def decorate_c_array_data (hexdata: str, var_name: str, var_type: str, newline_value: str): """ Place @hexdata into a valid C array named @var_name of C type @var_type. """ ret = var_type + " " + var_name + "[] = {" + newli...
def getDegenerateMatch(base): """ Given a degenerate base, returns all possible matches. Possible return values - a, g, c, t, n, x base = string, lowercase, degenerate base symbol """ base = base.lower() possibleMatches = { 'r':['a','g','n','x'], 'y':['c','t','n','x'], 's':['g','c','n','x'],...
def get_regionmap(plan): """ converts raw regionmap string to two-dimnesional regionmap """ length = plan["regionmap"]["length"] width = plan["regionmap"]["width"] raw = plan["regionmap"]["raw"].split(" ") regionmap = [[int(raw[i*width +j]) for j in range(width)]for i in range(length)] ...
def intersection_over_union(ground_truth_bbox, detection_box): """Computes IoU between two boxes. We Scale it with 100. Otherwise, small numbers are lost when transfered from python to matlab. Boxes should be lists in the format [center x, center y, width, height]""" # right-most of the left edges: ...
def bin2bytes(x): """Convert an array of bits (MSB first) into a string of characters.""" bits = [] bits.extend(x) bits.reverse() i = 0 out = b'' multi = 1 ttl = 0 for b in bits: i += 1 ttl += b * multi multi *= 2 if i == 8: i = 0 ...
def clear_state(dict_in): """Clear the state information for a given dictionary. Parameters ---------- dict_in : dict Input dictionary to be cleared. """ if type(dict_in) is dict: for i in dict_in: if 'state' in dict_in[i]: dict_in[i]['state'] = None...
def order(sentence: str) -> str: """Returns ordered sentence. Examples: >>> assert order("") == "" >>> assert order("is2 Thi1s T4est 3a") == "Thi1s is2 3a T4est" """ return " ".join( map( lambda item: item[1], sorted( map( ...
def exists_in_tree(node, n): """This function finds if an element exists in a tree or not by recursively traversing the tree input : current node and the element to be found output : returns True if it exists, False if not Time complexity : O(n), Space complexity : O(1) """ if node =...
def get_metrics(trial_list, metric): """Extract metric""" return [trial[metric] for trial in trial_list]
def case_est_noire(nv, nh): """ Determine si une case est noire ou blanche a partir de ses numeros nv et nh """ return (nv % 2 == 1 and nh % 2 == 0) or (nv % 2 == 0 and nh % 2 == 1)
def write_file(filename="", text=""): """writes to a utf-8 encoded text file """ with open(filename, 'w', encoding='utf-8') as myFile: return myFile.write(text)
def parse_entry(entry): """ Parse a single entry in JSON format, mostly flattening it. """ # Collect info for the root table root = { "root_id": entry["EGY_ROOT__ID"], "root_form": entry["EGY_ROOT__form"], "root_meaning_en": entry["EGY_ROOT__meaning_en"], } if entry[...
def get_outfile_name(name_base): """ Returns a name for a file. If a GMT object is given as input, uses `gmt.suffix` to produce a name for the file. If not, the file is understood to be a background file and a uuid is returned. """ outfile_name = name_base + '.csv' print('outfile name: ' + outfi...
def _build_coverage_cmd(cmd): """Infer the correct `coverage` command from the `check-contents` command.""" return cmd[:cmd.index('check-contents')] + ['coverage', '--path', '@', '--json']
def split_word_list_by_delimiter(word_list, keyphrase_delimiter, include_present_absent_delimiter=False, present_absent_delimiter=None): """ Convert a word list into a list of keyphrase, each keyphrase is a word list. :param word_list: word list of concated keyprhases, separated by a delimiter :param ke...
def list_to_sum(L): """Turns a list into a summation""" S = " + ".join(str(elem) for elem in L) S = S.replace("+ -","- ") return S
def list_to_tuple(maybe_list): """Datasets treat lists specially, so switch them to tuples.""" if isinstance(maybe_list, list): return tuple(maybe_list) return maybe_list
def create_payload(url, script="alert('test');"): """ Create the payload for the URL >>> create_payload("http://127.0.0.1/php?id=1") http://127.0.0.1/php?id=<script>alert('test');</script> """ data = url.split("=") open_and_close_script = ("<script>", "</script>") return data[0] + "=" + open_and...
def fix_epoch(epoch): """ Fix value of `epoch` to be epoch, which should be 10 or fewer digits long. :arg epoch: An epoch timestamp, in epoch + milliseconds, or microsecond, or even nanoseconds. :rtype: int """ try: # No decimals allowed epoch = int(epoch) except Exc...
def getPrimeFactors(n): """ Get all the prime factor of given integer @param n integer @return list [1, ..., n] """ lo = [1] n2 = n // 2 k = 2 while k <= n2: if (n // k)*k == n: lo.append(k) k += 1 return lo + [n,]
def createDict(data, index): """ Create a new dictionnay from dictionnary key=>values: just keep value number 'index' from all values. >>> data={10: ("dix", 100, "a"), 20: ("vingt", 200, "b")} >>> createDict(data, 0) {10: 'dix', 20: 'vingt'} >>> createDict(data, 2) {10: 'a', 20: 'b'} ...
def factorial(number): """ This function calculates the factorial of the given number. Numbers over 1000 can take over 10secs! :param number: Number to calculate :return: Returns the value of the number calculated """ def shrink_list(lst): """ This sub-function takes all the...
def repeat_0(a, repeat): """ """ o = [] for i in range(0,len(a)): for r in range(0,repeat): o.append(a[i]) return o
def average_number_of_groups(m, n): """ Split a data into N parts of approximate size . :param m: Total length of data to be split . :param n: Need to be divided into several portions . :return: list ,index +1 that should be split . """ base_num = m // n over_num = m % n ...
def rot32(v, bits): """Rotate the 32-bit value v left by bits bits.""" bits %= 32 # Make sure the term below does not throw an exception return ((v << bits) & 0xffffffff) | (v >> (32 - bits))
def _find_run_id(traces, trace_type, item_id): """Find newest run_id for a script or automation.""" for _trace in reversed(traces): if _trace["domain"] == trace_type and _trace["item_id"] == item_id: return _trace["run_id"] return None
def message_relay(msg): """ One global signal to relay messages to all participants. """ return msg + '<br />'
def seconds_difference(time_1, time_2): """ (number, number) -> number Return the number of seconds later that a time in seconds time_2 is than a time in seconds time_1. >>> seconds_difference(1800.0, 3600.0) 1800.0 >>> seconds_difference(3600.0, 1800.0) -1800.0 >>> seconds_dif...
def pad(nm): """pad(nm) - a function to pad an atom name with appropraiate spaces""" space = ' ' if len(nm) >= 4: return nm try: int(nm[0]) except ValueError: nm = ' ' + nm return nm + space[0:4-len(nm)]
def find_last_to_last(lis, elem_set) -> int: """Returns the index of last to last occurance of any element of elem_set in lis, if element is not found at least twice, returns -1.""" count = 0 for idx, elem2 in reversed(list(enumerate(lis))): if elem2 in elem_set: count += 1 i...
def resource_descriptor(session, Type='String', RepCap='', AttrID=1050304, buffsize=2048, action=['Get', '']): """[Get/Set Resource Descriptor] """ return session, Type, RepCap, AttrID, buffsize, action
def format_closure_comment(options: dict, idx: int) -> str: """ render an optional end of line comment after a ring-closing bond :param options: option dict :param idx: index :return: '-> ' + idx """ if options["terse"]: return "" return f"-> {idx}"
def get_copy(o, copy): """Returns copy of object.""" if copy: return copy(o) else: return o
def update_dict_path(base, path, value, default=dict): """ Set the dict path ``path`` on the dict ``base`` to ``value``. If the path does not yet exist, the callable ``default`` will be used to create it. A dict path is a way to represent an item deep inside a dict structure. For example, the dic...
def is_callable(obj) -> bool: """ Parameters ---------- obj: Any the object to be checked Returns ------- validator : bool returns True if object is callable raises ValueError otherwise. """ if not callable(obj): raise ValueError("Value mu...
def _stringify(value): """Convert a value into a string that will parse""" if value is None: return "NULL" elif value is True: return "TRUE" elif value is False: return "FALSE" elif isinstance(value, str): return '"' + value.replace('"', '\\"') + '"' else: ...