content stringlengths 42 6.51k |
|---|
def next_name(container, key):
"""
Given a container object and some key prefix, yield the next key with the
given prefix that is not contained into container.
"""
if key not in container:
return key
for i in range(1, 1000):
test = f"{key}_{i}"
if test not in container:
... |
def monthCode(month):
"""
perform month->code and back conversion
Input: either month nr (int) or month code (str)
Returns: code or month nr
"""
codes = ('F','G','H','J','K','M','N','Q','U','V','X','Z')
assert month>0 , 'Month number must be positive and >0'
if isins... |
def has_duplicates(t):
"""Takes a list returns True if any element appears more than once, otherwise False"""
seen = {}
for item in t:
if item in seen:
return True
else:
seen[item] = True
return False |
def is_iterator(obj) -> bool:
"""
Check if the input is an iterator by trying to call `next()` on it.
:param obj: any object
:return: `True` if input is an iterator, else `False`
"""
try:
next(obj, None)
return True
except TypeError:
return False |
def pad(bytestring, k=16):
"""
Pad an input bytestring according to PKCS#7
"""
l = len(bytestring)
val = k - (l % k)
return bytestring + bytearray([val] * val) |
def _get_template_params(template, param_values):
"""Return all required parameter values for the specified template.
:param dict template: Template JSON object.
:param dict param_values: User provided parameter values.
"""
param_keys = {}
try:
for param, values in template['parameters']... |
def list_to_comma_delimited(list_param):
"""Convert a list of strings into a comma-delimited list / string.
:param list_param: A list of strings.
:type list_param: list
:return: Comma-delimited string.
:rtype: str
"""
if list_param is None:
list_param = []
return ','.join(list_p... |
def is_image(name):
"""
Checks is given file an image
:param name: filename
:return: True is file is image
"""
extension = name.split('.')[-1]
if extension.lower() in ['jpg', 'png', 'bmp', 'jpeg']:
return True
return False |
def krylov_params(n_krylov=40, n_diag=100, tol_coef=0.01, max_restarts=30,
reorth=True):
"""
Bundles parameters for the Lanczos eigensolver. These control
the expense of finding the left and right environment tensors, and of
minimizing the effective Hamiltonians.
PARAMETERS
--... |
def is_odd(n: int) -> bool:
"""
Checks if a number is odd(lol).
:param n: The number.
:return: True if it is odd else false.
"""
return not (n % 2 == 0) |
def solution(n):
"""Returns the smallest positive number that is evenly divisible(divisible
with no remainder) by all of the numbers from 1 to n.
>>> solution(10)
2520
>>> solution(15)
360360
>>> solution(20)
232792560
>>> solution(22)
232792560
"""
i = 0
while 1... |
def dic2fileheader(dic):
"""
Convert a Python dictionary into a fileheader list
Does not repack status from bit flags
"""
head = [0] * 9
head[0] = dic["nblocks"]
head[1] = dic["ntraces"]
head[2] = dic["np"]
head[3] = dic["ebytes"]
head[4] = dic["tbytes"]
head[5] = dic["bbyt... |
def arg_list_type(args):
""" Returns a list of arguments """
new_args = []
for arg in args:
arg = [a.replace("\'","").replace("\"", "") for a in arg.split()]
new_args += arg
return new_args |
def normalize_cov_type(cov_type):
"""
Normalize the cov_type string to a canonical version
Parameters
----------
cov_type : str
Returns
-------
normalized_cov_type : str
"""
if cov_type == 'nw-panel':
cov_type = 'hac-panel'
if cov_type == 'nw-groupsum':
cov_... |
def dashed_line(num: int, dash: str = '#') -> str:
"""Returns a string composed of num dashes"""
temp = ""
for i in range(num):
temp += dash
return temp |
def _FindRuleTriggerFiles(rule, sources):
"""Find the list of files which a particular rule applies to.
Arguments:
rule: the rule in question
sources: the set of all known source files for this project
Returns:
The list of sources that trigger a particular rule.
"""
rule_ext = rule['extension']
... |
def sigma(n: int) -> int:
"""Returns the sum of integers from 1..n"""
return (n * n + n) // 2 |
def float_or_zero(x):
"""
:param x: any value
:return: converted to float if possible, otherwise 0.0
"""
if x is None:
return 0
try:
return float(x)
except ValueError:
return 0.0 |
def is_between(lo, val, hi) -> bool:
"""Shorthand for `(lo <= val <= hi) or (lo >= val >= hi)`."""
return (lo <= val <= hi) or (lo >= val >= hi) |
def _decideStrFormat(string):
"""
take the character that is not closest to the beginning or end
"""
single_quote_left = string.find("'")
single_quote_right = string.rfind("'")
quote_left = string.find('"')
quote_right = string.rfind('"')
if single_quote_left == -1 and not quote_left ==... |
def unlucky_number(numbers):
"""
# Takes in a list of numbers and adds the elements up.
# Returns True if '4' is in the calculated sum and False if not.
>>> unlucky_number([1,2,3,4])
False
>>> unlucky_number([1,2,3,4,4])
True
# Add at least 3 doctests below here #
>>> unlucky_numbe... |
def _round_partial(value, grid_spacing):
"""Round to nearest point on a grid with a given grid_spacing."""
return round(value / grid_spacing) * grid_spacing |
def fix_django_headers(meta):
"""
Fix this nonsensical API:
https://docs.djangoproject.com/en/1.11/ref/request-response/
https://code.djangoproject.com/ticket/20147
"""
ret = {}
for k, v in meta.items():
if k.startswith("HTTP_"):
k = k[len("HTTP_"):]
elif k not in... |
def extend(s, var, val):
"""
Returns a new dict with var:val added.
"""
s2 = {a: s[a] for a in s}
s2[var] = val
return s2 |
def get_value_float(data, id, required=False):
"""
Finds a value with the given id among data and returns its value. The data are strings with one
letters (id), followed by numbers. There are no spaces.
Input:
data: List of strings (something like ['o1.2', 'r45', 't0.9'])
id: Id of the item to find - its str... |
def _format_time(total_seconds: float) -> str:
"""Format a time interval in seconds as a colon-delimited string [h:]m:s"""
total_mins, seconds = divmod(int(total_seconds), 60)
hours, mins = divmod(total_mins, 60)
if hours != 0:
return f"{hours:d}:{mins:02d}:{seconds:02d}"
else:
retur... |
def generate_summary_str(summary_items):
""" Generates formatted string containing CloudTrail summary info.
Args:
summary_items (list): List of tuples containing CloudTrail summary info.
Returns:
(string)
Formatted string containing CloudTrail summary info.
"""
return '\t'... |
def chunk(lst, parts):
"""
Divides a list into specified number of sublists.
Args:
lst (list): The list to chunked.
parts (int): The number of parts the list should be divided into.
Returns:
list: Chunked list.
"""
k, m = divmod(len(lst), parts)
chunks = [lst[i * ... |
def check_for_balanced_parantheses(expression):
"""
Finds out how balanced an expression is.
With a string containing only brackets.
>>> is_matched('[]()()(((([])))')
False
>>> is_matched('[](){{{[]}}}')
True
"""
opening = tuple('({[')
closing = tuple(')}]')
mapping = dict(z... |
def _decision_mad(x,mu,ma):
"""
Outliers with mad
"""
if x!=0 and ((abs(x-ma)/mu)>1.4826):
return 1
else: return 0 |
def line_with_jacoco_test_footer(line, report_type):
"""Check if the given string represents JaCoCo unit test footer."""
return report_type == "jacoco" and line == "Code coverage report END" |
def truefalse(prefix, parsed_args, **kwargs):
"""
Returns True and False.
:param prefix: The prefix text of the last word before the cursor on the command line.
:param parsed_args: The result of argument parsing so far.
:param kwargs: keyword arguments.
:returns list: True and False.
"""
... |
def _get_connect_string(backend, user, passwd, database):
"""
Try to get a connection with a very specific set of values, if we get
these then we'll run the tests, otherwise they are skipped
"""
if backend == "postgres":
backend = "postgresql+psycopg2"
elif backend == "mysql":
ba... |
def MatchesSuffixes(filename, suffixes):
"""Returns whether the given filename matches one of the given suffixes.
Args:
filename: Filename to check.
suffixes: Sequence of suffixes to check.
Returns:
Whether the given filename matches one of the given suffixes.
"""
suffix = filename[filename.rfin... |
def should_dict_attr_be_excluded(map_option_name, option_key, exclude_list):
"""An entry for the Exclude list for excluding a map's key is specifed as a dict with the map option name as the
key, and the value as a list of keys to be excluded within that map. For example, if the keys "k1" and "k2" of a map
o... |
def _is_user_author_or_privileged(cc_content, context):
"""
Check if the user is the author of a content object or a privileged user.
Returns:
Boolean
"""
return (
context["is_requester_privileged"] or
context["cc_requester"]["id"] == cc_content["user_id"]
) |
def paramsDictNormalized2Physical(params, params_range):
"""Converts a dictionary of normalized parameters into a dictionary of physical parameters."""
# create copy of dictionary
params = dict(params)
for key, val in params.items():
params[key] = val * (params_range[key][1]-params_ran... |
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'red' if (val != 0 and type(val) !=str) else 'black'
return 'color: %s' % color |
def paths_are_not_structured(paths):
"""
returns true if the list of paths are not yet file system structured.
i.e. if not all paths start with the root path (contribution label)
"""
if not paths:
return False
root = paths[0][: paths[0].find('/', 1)]
for path in reversed(paths):
... |
def factorize(num:int) ->list:
"""
return a list of factors of a given number
param: int
return: list of int
"""
num = abs(num)
root = int(num ** 0.5) + 1
i = 1
bound = num
fact = []
while i < bound and i <= root:
if num % i == 0:
fact.append(i)
... |
def frequency(tol_str, tar_str):
"""Generate the frequency of tar_str in tol_str.
:param tol_str: mother string.
:param tar_str: substring.
"""
i, j, tar_count = 0, 0, 0
len_tol_str = len(tol_str)
len_tar_str = len(tar_str)
while i < len_tol_str and j < len_tar_str:
if tol_str[i... |
def reverse_dict_list(org):
"""Reverses dict {a: [b,c]} to {b:a, c:a}."""
newdict = {}
for key, value in org.items():
for string in value:
newdict[string] = key
return newdict |
def test_files(paths):
"""
Get the number of the test related files."
"""
# This feature assumes that test files contain word "test
test_files_count = len([path for path in paths if "test" in path.lower()])
return test_files_count |
def cleanp(stx):
"""
Simple string cleaner
"""
return stx.replace("(", "").replace(")", "").replace(",", "") |
def _dot_to_underscore_and_strip_numeric_suffix(name: str) -> str:
"""
e.g. "library_preparation_protocol_0.json" -> "library_preparation_protocol_json"
"""
name = name.replace('.', '_')
if name.endswith('_json'):
name = name[:-5]
parts = name.rpartition("_")
if name != parts... |
def concatenate(*args):
"""
If no argument is None, then join all strings.
:param args: Can be strings, MyString objects or None
:return: None or string.
"""
for e in args:
if e is None:
return None
return ''.join([str(e) for e in args]) |
def list_to_map(item_list, key_name):
"""
Given a list of dicts/objects return a dict mapping item[key_name] -> item
:param item_list:
:param key_name:
:return:
"""
return {x.pop(key_name): x for x in item_list} |
def compare_dict(da, db):
"""
Compare differencs from two dicts
"""
sa = set(da.items())
sb = set(db.items())
diff = sa & sb
return dict(sa - diff), dict(sb - diff) |
def _attributeLinesToDict(attributeLines):
"""Converts a list of obo 'Term' lines to a dictionary.
:param attributeLines: a list of obo 'Term' lines. Each line contains a key
and a value part which are separated by a ':'.
:return: a dictionary containing the attributes of an obo 'Term' entry.
... |
def power_limit(power, clip_level = 100.0):
"""Compares input power level against a clip value, and returns a clipped value if level is exceeded."""
if power > clip_level:
output = clip_level
elif power < -clip_level:
output = -clip_level
else:
output = power
return ... |
def selection_sort(vals):
"""Sort the given array using selection sort."""
for i in range(len(vals) - 1):
min_index = i
for j in range(i + 1, len(vals)):
if vals[j] < vals[min_index]:
min_index = j
if min_index != i:
vals[i], vals[min_index] = vals... |
def chi_psi_a(a, chi_opt):
""" return value of screening potential at given time """
phi = chi_opt["phi"]
n = chi_opt["n"]
phi *= pow(a, (5.-2*n)/(1.-n))
return phi |
def index_page(request):
"""The MOE index view.
.. http:get:: /
"""
return {
'nav_active': 'home',
} |
def _totalUniqueWords(dataset, index):
"""
Given a dataset, compute the total number of unique words at the given index.
GIVEN:
dataset (list) list of lists, where each sublist is a document
index (int) index in dataset to count unique words
RETURN:
unique_words (int... |
def voigt_avg(M1, M2, f1, f2):
"""
Voight average for a 2 mineral mixture
Usage:
M = voigt_avg(M1, M2, f1, f2)
Inputs:
M1 & M2 = Elastic moduli for each phase
f1 & f1 = Volume fraction of each phase
Output:
M = Voigt average of elastic moduli
"""
... |
def getAverage(items):
"""
Gets the average amount in a list.
Args:
items (list): must contain floats or integers.
Returns:
(integer, float): average of all the items in list.
"""
return sum(items) / len(items) |
def retrieve_array(digits): # O(N)
"""
Take a number and transform it into an array
>>> retrieve_array(123456789)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> retrieve_array(-123456789)
[-1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
string = "{0}".format(digits) ... |
def is_valid(map, index):
""" Verify that the index is in range of the map """
row, column = index
return 0 <= row < len(map) and 0 <= column < len(map[row]) |
def already_visited(string):
"""
Helper method used to identify if a subroutine call or definition has
already been visited by the script in another instance
:param string: The call or definition of a subroutine/function
:return: a boolean indicating if it has been visited already or not
"""
... |
def is_sas_url(s: str) -> bool:
"""
Placeholder for a more robust way to verify that a link is a SAS URL.
99.999% of the time this will suffice for what we're using it for right now.
"""
return (s.startswith(('http://', 'https://')) and ('core.windows.net' in s)
and ('?' in s)) |
def sort_windows(l):
"""Sort a list of sliding windows."""
parsed_l = [w.split(".") for w in l]
parsed_l = [
(
int(w[0][1:].split("to")[0]),
int(w[0][1:].split("to")[1]),
int(w[1][1:].split("to")[0]),
int(w[1][1:].split("to")[1]),
)
for... |
def binaryformat(value):
"""Convert a binary value."""
# Escape #^-\]
# We include # in case we are using (?x)
if value in (0x23, 0x55, 0x5c, 0x5d):
c = "\\x%02x\\x%02x" % (0x5c, value)
else:
c = "\\x%02x" % value
return c |
def getOriginalFileName(fileName, fileExtension=".c"):
""" Strips a file name off digits and underscores and returns the original file name """
originalFileName = fileName.replace("_","").replace(fileExtension,"")
# Now remove the digits
for i in range(10):
originalFileName = originalFileName.rep... |
def leap_check(year) -> str:
"""Check if a year is a leap year.
:return: A string telling us weather or not it is a leap year.
"""
if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0):
return f"{year} is a leap year!"
else:
return f"{year} is not a leap year!" |
def get_script_dir(follow_symlinks=True):
"""https://stackoverflow.com/questions/3718657/how-to-properly-determine-current-script-directory/22881871#22881871"""
import inspect
import os
import sys
if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
path = os.path.abspath(sys.e... |
def describe_pe_direction(metadata: dict, config: dict) -> str:
"""Generate description of phase encoding direction."""
dir_str = config["dir"][metadata["PhaseEncodingDirection"]]
dir_str = "phase encoding: {}".format(dir_str)
return dir_str |
def relative_spread_fitness(input_phenotype):
"""
Punish high spread of disease.
:param input_phenotype:
:type input_phenotype:
:return:
:rtype:
"""
infected = input_phenotype["number_total_infected"]
# infected = input_phenotype["number_currently_infected"]
agents = input_phenotype["number_of_agents"]
rela... |
def cleanIDs(idString):
"""
Convert search engine protein IDs to UniprotIDs
Exclude contaminants
"""
#the format of ID is like ??|UNIPROTID|???, ??|UNIPROTID|???, ....
elements = [e.split("|") for e in idString.split(",")]
elements = [z for z in elements if len(z) == 3]
if len(elements) ... |
def xor_swap(i, j):
"""Swap with exclusive or"""
i = i ^ j
j = i ^ j
i = i ^ j
return i, j |
def html_escape(text):
"""Escape HTML/XML special characters (& < >) in a string that's to be embedded in a text part of an HTML/XML document.
For escaping attribute values use html_attr_escape() - attributes need a different set of special characters to be escaped.
"""
return text.replace('&', '&')... |
def _overlaps(a, b):
"""
Return the amount of overlap, between a and b.
If >0, how much they overlap
If 0, they are book-ended
If <0, distance
Parameters
----------
a, b : list
lists of two numerals denoting the boarders of ranges.
Returns
-------
overlap : float
... |
def get_any_of(getter, possible_keys, default=None):
"""Search for the value of any of `possible_keys` in `dictionary`, returning `default` if none are found.
>>> get_any_of( {"A":1}, ["C","D","A"], "UNDEFINED")
1
>>> get_any_of( {"X":1}, ["C","D","A"], "UNDEFINED")
'UNDEFINED'
"""
for... |
def indent(s, amount=2):
"""
Indents a block of text (useful for debug purposes).
Not intended for use in indenting table cells!
"""
results = []
for line in s.split('\n'):
results.append(" "*amount + line)
return "\n".join(results) |
def avg(l):
"""Returns the average of a list of numbers."""
if not l:
return None
return sum(l)/len(l) |
def note(gesamt, eins, vier, feinheit):
"""
Berechnet die Note zu einer gegebenen Punktzahl
"""
steigung = 3./(vier-eins)
achsenab = 4 - steigung * vier
notenwert = steigung * gesamt + achsenab
if notenwert <= 1:
return 1
if notenwert >= 6:
return 6
return round(round... |
def default_error_handler(e):
""" Default error handler"""
return {'message': 'An unhandled exception occurred'}, 500 |
def clean_sa_ea(dictio, decreasing_factor):
"""
Clean start and end activities by using decreasing factor
Parameters
-------------
dictio
Dictionary of start and end activities
decreasing_factor
Decreasing factor
Returns
-------------
cleaned_dictio
Cleaned ... |
def cluster(d):
"""
Utility function
"""
clusters = {}
for key, val in d.items():
clusters.setdefault(val, []).append(key)
return clusters |
def _prep_categorical_return(truth, description, verbose):
"""
Return `truth` and `description` if `verbose is True` else return
`description` by itself.
"""
if verbose:
return truth, description
return truth |
def __contains_kevin_bacon__(tweet):
"""
Check if a tweet contains Kevin Bacon, Kevin_Bacon, or KevinBacon (case
insensitive).
Args:
tweet: tweet text
Return:
True if the tweet text contains a form of "Kevin Bacon"
"""
tweet_text = tweet.lower()
if "kevin bacon" in twe... |
def bytes_to_number(b, endian='big'):
"""
Convert a string to an integer.
:param b:
String or bytearray to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case version of str... |
def shift_this(number, high_first=True):
"""Utility method: extracts MSB and LSB from number.
Args:
number - number to shift
high_first - MSB or LSB first (true / false)
Returns:
(high, low) - tuple with shifted values
"""
low = (number & 0xFF)
high = ((number >> 8) & 0xFF)
i... |
def normalize_trailing_slash(path_info):
"""Removes a trailing slash from the given path, if any."""
# Remove trailing slash, unless it's the only char
if len(path_info) > 1 and path_info[-1] == '/':
return path_info[:-1]
# No need to change anything
else:
return path_info |
def to_bulk(a, size=100):
"""Transform a list into list of list. Each element of the new list is a
list with size=100 (except the last one).
"""
r = []
qt, rm = divmod(len(a), size)
i = -1
for i in range(qt):
r.append(a[i * size:(i + 1) * size])
if rm != 0:
r.ap... |
def get_months_in_range(startdate, enddate):
"""Enumerates all months from startdate to enddate
Args:
startdate: start of the list of dates
enddate: end of the list of dates, likely today
Returns:
list of months in iso8601 format: yyyymm
"""
result = []
startmonth = [int... |
def existing_gene(store, panel_obj, hgnc_id):
"""Check if gene is already added to a panel."""
existing_genes = {gene["hgnc_id"]: gene for gene in panel_obj.get("genes", {})}
return existing_genes.get(hgnc_id) |
def setDelay(fps):
"""
@param fps: Indicates how many frames per second to extract from the video
@type fps: Integer between 1 and 1000
@return: 1 if value is not correct
"""
if 1 <= fps <= 1000:
global frameDelay
frameDelay = round(1000 / fps)
else:
return 1 |
def extendedEuclideanAlgorithm(a, b):
"""
Returns a three-tuple (gcd, x, y) such that
a * x + b * y == gcd, where gcd is the greatest
common divisor of a and b.
This function implements the extended Euclidean
algorithm and runs in O(log b) in the worst case.
"""
s, old_s = 0, 1
t, o... |
def lam(m, f, w):
"""Compute lambda"""
s = 0
for i in range(len(f)):
s += f[i] * w[i]
return float(m)/float(s) |
def search(obj, attribute, _trace=''):
"""
Find a key or attribute within a dictionary or object.
This function facilitates finding nested key(s) or attributes within an object,
by searching recursively through keys or attributes.
Args:
obj: A dict or class with __dict__ attribute
... |
def _dump_multipolygon(obj, fmt):
"""
Dump a GeoJSON-like MultiPolygon object to WKT.
Input parameters and return value are the MULTIPOLYGON equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mp = 'MULTIPOLYGON (%s)'
polys = (
# join the polygons in the multipol... |
def bid_for_bider(bider, bids, item):
"""
Returns the bid the bider put on item
"""
return bids[item] if item in bids.keys() else 0 |
def get_cum_probs_for(distribution):
"""Generate cumulative probabilities from the given distribution."""
cum_probs = []
total_weight = sum((weight for elem, weight in distribution))
prev_cutoff = 0
for elem, weight in distribution:
if weight == float("inf"):
cutoff = 1
e... |
def lastSectionPair(incomplete):
"""
Given an incomplete command text of a section, return the last (possibly
incomplete) key-value pair
"""
lastSection = incomplete.split(";")[-1]
x = [x.strip() for x in lastSection.split(":", 1)]
if len(x) == 1:
return x[0], ""
return x |
def size_to_bytes(size):
""" Return the size as a bytes object.
@param int size: a 32-bit integer that we want to convert to bytes
@rtype: bytes
>>> list(size_to_bytes(300))
[44, 1, 0, 0]
"""
# little-endian representation of 32-bit (4-byte)
# int size
return size.to_byt... |
def api_keys(request): # pylint: disable=unused-argument
"""
Pass a `APIKEYS` dictionary into the template context, which holds
IDs and secret keys for the various APIs used in this project.
"""
return {
"APIKEYS": {
}
} |
def filterSame(set1, set2):
# S1: Using for loop
"""
results = set()
for i in set1:
if i not in set2:
results.add(i)
print(results)
return results
"""
# S2: Using .difference()
return set1.difference(set2) |
def mean(data, window_size):
"""Get the data mean according to the window size.
:param data: A list of values.
:param window_size: A window size.
:return: The mean value.
"""
return float(sum(data)) / window_size |
def unparse_address(scheme, loc):
"""
Undo parse_address().
>>> unparse_address('tcp', '127.0.0.1')
'tcp://127.0.0.1'
"""
return "%s://%s" % (scheme, loc) |
def fields_match(string_1,
string_2,
field_separator=':',
allow_empty_fields=True):
"""Match fields of two strings, separated by a |field_separator|. Empty fields
can be ignored via |allow_empty_fields| flag."""
if string_1 is None or string_2 is None:
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.