content stringlengths 42 6.51k |
|---|
def increment_mean(pre_mean, new_data, sample_size):
"""
Compute incremental mean
"""
inc_mean = pre_mean + (new_data-pre_mean) / sample_size
return inc_mean |
def serialize_args(*argnames, **full_args):
"""
Split positional args from a set of keyword args
Args:
argnames (List[str]): Names of args to make positional
full_args (dict): Keyword arguments dict
Returns:
Tuple of (positional args list, keyword args dict).
"""
serial... |
def balanced_eq(x, z, y):
"""Gradient of the max operator with tie breaking.
Args:
x: The left value
z: The maximum of x and y
y: The right value
Returns:
The gradient of the left value i.e. 1 if it is the maximum, 0.5 if they are
equal and 0 if it was not the maximum.
"""
return (x == z... |
def _to_latex(string):
"""Latex-decorate a string."""
return ('$' + string + '$') |
def siqs_choose_nf_m(d):
"""Choose parameters nf (sieve of factor base) and m (for sieving
in [-m,m].
"""
# Using similar parameters as msieve-1.52
if d <= 34:
return 200, 65536
if d <= 36:
return 300, 65536
if d <= 38:
return 400, 65536
if d <= 40:
return... |
def mean(values):
"""Calculate sample mean."""
return sum(values) / len(values) |
def get_label_from_directory(directory):
"""
Function to set the label for each image. In our case, we'll use the file
path of a label indicator. Based on your initial data
Args:
directory: string
Returns:
int - label
Raises:
NotImplementedError if unknow... |
def read_files(filenames):
"""
Reads a file line by line
Args:
filenames : list of str
a list of string containing the paths to the files used to learn the
embeddings
Returns:
sents : list of list of str
a list containing the words, line per line
"... |
def api_runner_removal(repo: str) -> str:
"""Helper function which returns the API endpoint for runner removal.
Parameter
---------
repo
Repository in the format "some_user/repo_name".
Returns
-------
String containing the full API endpoint to obtain token for runner removal.
... |
def md_heading_style_name(level: int) -> str:
"""Returns the name of the text style used for Markdown headings of the given level."""
assert 1 <= level <= 6
return f"md-h{level}" |
def get_access(name):
"""Get access based on name
In Python __var__ refers to a private access
_var refers to protected access
and var would refer to public access
"""
assert isinstance(name, str), "Expecting name to be a string"
if len(name) > 4 and "__" == name[:2] and "__" == name[-2:]:
... |
def truncate_labels(labels, min_doc_count):
"""
labels is an array of label sets.
remove labels that occur in less than min_doc_count documents
Sample input:
[
['foo','bar','baz'],
['foo','quux']
]
Sample output (for min_doc_count=2):
[
... |
def _eoltype(data):
"""Guess the EOL type of a file"""
if b'\0' in data: # binary
return None
if b'\r\n' in data: # Windows
return b'\r\n'
if b'\r' in data: # Old Mac
return b'\r'
if b'\n' in data: # UNIX
return b'\n'
return None |
def cost_memory_removed_mod(
size12, size1, size2, k12, k1, k2,
costmod=1, usesizes=True,
):
"""The default heuristic cost, corresponding to the total reduction in
memory of performing a contraction.
"""
if usesizes:
return size12 - costmod * (size1 + size2)
return len(k12) - costmod... |
def _is_ipy_notebook(node_id: str) -> bool:
"""
Returns True if node_id is an IPython notebook, otherwise False.
"""
fpath = node_id.split("::")[0]
return fpath.endswith(".ipynb") |
def iter_ith( it, item ):
"""Return i'ith item from iterator"""
for i, v in enumerate( it ):
if i == item: return v
raise IndexError( "iter_ith: iterator does not have item number " + str( item ) ) |
def maximum_value(maximum_weight, items):
"""
Find the best solution for the knapsack problem
"""
_dp = [0 for i in range(maximum_weight + 1)]
chosen_items = [[] for i in range(maximum_weight + 1)]
for i in range(maximum_weight):
for index, item in enumerate(items):
if in... |
def extent(lst):
"""Get extent (dimensions object given by lst)."""
vecs = zip(*lst)
return [max(v) - min(v) for v in vecs] |
def imap_helper(args):
"""
Helper function for imap.
This is needed since built-in multiprocessing library does not have `istarmap` function.
If packed arguments are passed, it unpacks the arguments and pass through the function.
Otherwise, it just pass the argument through the given function.
... |
def valid_cmd(cmd: str):
"""
Returns true if the given command is valid.
Valid commads are of the form:
ACTION TICKER AMOUNT
"""
if cmd in ("q" or "quit"):
return False
tokens = cmd.split(" ")
if len(tokens) != 3:
print("Incorrect format: require ACTION TICKER AMOUN... |
def convert_to_int(byte_arr):
"""Converts an array of bytes into an array of integers"""
result = []
for i in byte_arr:
result.append(int.from_bytes(i, byteorder='big'))
#introducem termenul liber
result.insert(0, 1)
# print(result)
return result |
def precompute_idfs(wglobal, dfs, total_docs):
"""Pre-compute the inverse document frequency mapping for all terms.
Parameters
----------
wglobal : function
Custom function for calculating the "global" weighting function.
See for example the SMART alternatives under :func:`~gensi... |
def _i_get(data, i_map, key):
"""Get an item from data insensitively.
:param data: Data with sensitive keys
:type data: Dict
:param i_map: Map of lowercase keys to real keys.
:type i_map: Dict
:param key: Sensitive key
:type key: String
:returns: Value
:rtype: object
"""
key... |
def upper(value):
"""
returns the uppercase copy of input string.
:param str value: string to make uppercase.
:rtype: str
"""
return value.upper() |
def _categorizeVector(v):
"""
Takes X,Y vector v and returns one of r, h, v, or 0 depending on which
of X and/or Y are zero, plus tuple of nonzero ones. If both are zero,
it returns a single zero still.
>>> _categorizeVector((0,0))
('0', (0,))
>>> _categorizeVector((1,0))
('h', (1,))
>>> _categorizeVector((0... |
def set_low_byte(target, lo_byte):
"""
Sets the low byte of a 16 bit (or longer) target value (*not* a little endian word!) to lo_byte
"""
return (target & 0xFF00) + lo_byte |
def is_valid_arrangement(arrangement, song):
"""
Validates an arrangement against a song. Returns True (valid) or
False (invalid). Valid means that every setion specified in the
arrangement exists in the song's specified sections.
:param song: a dictionary conforming to the Song object data model.
... |
def common_substring(word1, word2):
"""
Returns the common substring between word1 and word2
"""
ret = ""
for a, b in zip(word1, word2):
if a == b:
ret += a
return ret |
def unique_data(x, y, doc_ids):
"""Remove duplicate provisions"""
print('Removing duplicate provisions')
seen = set([])
uniq_x, uniq_y, uniq_doc_ids = [], [], []
for x_, y_, doc_id in zip(x, y, doc_ids):
if not x_ in seen:
uniq_x.append(x_)
uniq_y.append(y_)
... |
def str_to_value(input_str):
"""
Convert data type of value of dict to appropriate one.
Assume there are only three types: str, int, float.
"""
if input_str.isalpha():
return input_str
elif input_str.isdigit():
return int(input_str)
else:
return float(input_str) |
def is_required(param):
"""
:param param:
:return:
"""
if "?" in param:
return False
else:
return True |
def get_matched_midi_md5(msd_id: str, msd_score_matches: dict):
"""
Returns the MD5 of the matched MIDI from its MSD id.
:param msd_id: the MSD id
:param msd_score_matches: the MSD score dict, use get_msd_score_matches
:return: the matched MIDI MD5
"""
max_score = 0
matched_midi_md5 = None
for midi_m... |
def ternary(value, true_val, false_val):
""" value ? true_val : false_val """
if value:
return true_val
else:
return false_val |
def _subsequence(s, c):
"""
Takes as parameter list like object s and returns the length of the longest
subsequence of s constituted only by consecutive character 'c's.
Example: If the string passed as parameter is "001000111100", and c is '0',
then the longest subsequence of only '0's has length 3.... |
def matrix_divided(matrix, div):
"""divides all elements of a matrix"""
if (matrix == [] or matrix == [[]] or
type(matrix) is not list or
not all(type(row) is list for row in matrix)):
raise TypeError("matrix must be a matrix (list of lists) "
... |
def ordered(state):
"""Returns an ordered version of the state (to improve node pruning)."""
sorted_state = sorted(zip(state[::2], state[1::2]))
return tuple(item for subl in sorted_state for item in subl) |
def _refs(r):
"""ref function in perl - called when followed by a backslash"""
_ref_map = {"<class 'int'>": 'SCALAR', "<class 'str'>": 'SCALAR',
"<class 'float'>": 'SCALAR', "<class 'NoneType'>": 'SCALAR',
"<class 'list'>": 'ARRAY', "<class 'tuple'>": 'ARRAY',
... |
def compress(word):
"""Return 'a3b2c4' if input is 'aaabbcccc'"""
result = []
counter = 0
word = word.lower()
last = word[0]
for i in word:
if last == i:
counter += 1
else:
result.append(last)
result.append(str(... |
def calc_assignment_average(assignment_list):
"""
Function that will take in a list of assignments and return
a list of average grades for each assignment
"""
return [sum(grades)/len(grades) for grades in assignment_list] |
def is_power2(num):
"""Test if number is a power of 2.
Parameters
----------
num : int
Number.
Returns
-------
b : bool
True if is power of 2.
Examples
--------
>>> is_power2(2 ** 3)
True
>>> is_power2(5)
False
"""
num = int(num)
return ... |
def _cmplx_negate_ ( s ) :
"""Negation:
>>> v = ...
>>> v1 = -v
"""
return -complex ( s ) |
def shell_sort(to_be_sorted):
"""
Subquadratic
:param to_be_sorted:
:return:
"""
if len(to_be_sorted) < 2:
return to_be_sorted
gap = len(to_be_sorted) // 2
while gap > 0:
for i in range(gap, len(to_be_sorted)):
j = i
while to_be_sorted[j - gap]... |
def format_proxies(proxy_host, proxy_port, proxy_user=None, proxy_password=None):
"""Sets proxy dict for requests."""
PREFIX_HTTP = 'http://'
PREFIX_HTTPS = 'https://'
proxies = None
if proxy_host and proxy_port:
if proxy_host.startswith(PREFIX_HTTP):
proxy_host = proxy_host[len(... |
def check_cgal_params(max_facet_distance, max_cell_circumradius, voxelsize):
"""Check CGAL mesher parameters.
# https://github.com/nschloe/pygalmesh#volume-meshes-from-surface-meshes
Parameters
----------
max_facet_distance
max_cell_circumradius
voxelsize : float
Image voxel size.
... |
def windowfy(_value):
"""
Turn backslashes into forward slashes
:param _value: A string value
"""
return _value.replace("/", "\\") |
def expandtabs(s, tabstop=8, ignoring=None):
"""Expand tab characters `'\\\\t'` into spaces.
:param tabstop: number of space characters per tab
(defaults to the canonical 8)
:param ignoring: if not `None`, the expansion will be "smart" and
go from one tabstop to th... |
def remove_mongo_date(resources: list) -> list:
"""Utility function to remove and flatten nested $date properties"""
res = []
for document in resources:
updated_document = document.copy()
for field, value in document.items():
if isinstance(value, dict) and "$date" in value:
... |
def spell(t):
"""Returns spelled representation of time"""
units = [(0.000001, 'microsecond', 'microseconds'),
(0.001, 'milisecond', 'miliseconds'),
(1, 'second', 'seconds'),
(60, 'minute', 'minutes'),
(60 * 60, 'hour', 'hours'),
]
i = 0
a... |
def get_eta_params(param_dict):
"""
Extract and return parameters from dictionary for all
forms other than the powerlaw form
"""
rScale = param_dict['rScale']
rc = param_dict['rc']
etaScale = param_dict['etaScale']
lambdaH = param_dict['lambdaH']
B = param_dict['B']
F = param_di... |
def containsNearbyDuplicate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
d={}
for i in range(len(nums)):
if nums[i] in d and i-d[nums[i]] <= k:
return True
d[nums[i]]=i
return False |
def check_all_values(base, target, tolerance=1e-15):
"""
Check the deviation of each element of two data arrays.
:param base: usually data arrays
:param target: usually data arrays
:param tolerance: max allowed deviation
:return: boolean, True for pass
"""
rtn = True
# sanity check
... |
def group_events(events):
"""
Groups events by ID, station, instrument and channel code.
"""
grouped = []
grouped_ids = []
for i, e in enumerate(events):
if i in grouped_ids:
continue
group_tag = e['id'] + e['station'] + e['instrument']
current_group = [e]... |
def _get_result_color(time_taken):
"""Get time taken result color."""
time_taken_ms = time_taken * 1000
if time_taken_ms <= 1000:
color = "green"
elif time_taken_ms <= 3000:
color = "yellow"
else:
color = "red"
return color |
def _get_ascii_resolution(numeric_str):
"""Determines the maximum resolution of an ascii-encoded numerical value
Necessary because HPSS logs contain numeric values at different and
often-insufficient resolutions. For example, tiny but finite transfers can
show up as taking 0.000 seconds, which results... |
def bbox_str_to_list(bbox: str):
""" Parse the bbox query param and return a list of floats """
bboxList = bbox.split(',')
return list(map(float, bboxList)) |
def dict_deep_overlay(defaults, params):
"""If defaults and params are both dictionaries, perform deep overlay (use params value for
keys defined in params), otherwise use defaults value"""
if isinstance(defaults, dict) and isinstance(params, dict):
for key in params:
defaults[key] =... |
def _locations_mirror(x):
"""
Mirrors the points in a list-of-list-of-...-of-list-of-points.
For example:
>>> _locations_mirror([[[1, 2], [3, 4]], [5, 6], [7, 8]])
[[[2, 1], [4, 3]], [6, 5], [8, 7]]
"""
if hasattr(x, '__iter__'):
if hasattr(x[0], '__iter__'):
return list... |
def is_disabled(context, name):
"""Whether a specific pattern is disabled.
The context object might define an inclusion list (includes) or an exclusion list (excludes)
A pattern is considered disabled if it's found in the exclusion list or
it's not found in the inclusion list and the inclusion list is ... |
def multiplicative_inverse(a, b):
"""
Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb
"""
# r = gcd(a,b) i = multiplicitive inverse of a mod b
# or j = multiplicitive inverse of b mod a
# Neg return values for i or j are made positive mod b or a respectively
# Iterateiv... |
def bslice(high, low=None):
"""
Represents: the bits range [high : low] of some value. If low is not given,
represents just [high] (only 1 bit), which is the same as [high : high].
"""
if low is None:
low = high
return slice(low, high + 1) |
def _MakeTile(repeated_string):
"""Make exactly 1Mb tile of the repeated string."""
total_size = 1024*1024
tile = repeated_string * (total_size // len(repeated_string))
tile += repeated_string[:total_size % len(repeated_string)]
return tile |
def _todo_recordgroup_create_values(coll_id="testcoll", group_id="testgroup",
render_type="Text", value_mode="Value_direct",
update="Field"):
"""
Entity values used when creating a group entity
"""
return (
{ 'rdfs:label': "%s %s/_field/%s"%(update, coll_id, grou... |
def complement(base: str) -> (str):
"""
Complement the base with respect to the IUPAC code.
:param base: the base to complement
:return: the complemented base
"""
# assert base in IUPAC_BASES
if base == 'A':
return 'T'
elif base == 'T':
return 'A'
elif base... |
def DecrementPatchNumber(version_num, num):
"""Helper function for `GetLatestVersionURI`.
DecrementPatchNumber('68.0.3440.70', 6) => '68.0.3440.64'
Args:
version_num(string): version number to be decremented
num(int): the amount that the patch number need to be reduced
Returns:
string: decremente... |
def tl(lst):
""" Returns all but first element from list if it len(list) > 1 """
return lst[1:] if len(lst) > 1 else None |
def _replace_none(lst, repl=""):
"""Auxiliary function to replace None's with another value."""
return ['' if v is None else v for v in lst] |
def _parse_units(units):
"""
Get the units factors regarding the cgs system
"""
# Get all the physical magnitudes
mags = []
pwrs = []
# Sign of the power
sign_pwr = 1
val_pwr = 1
# Multiplications symbols
mul_signs = [' ', '*']
# Auxiliar units
aux_unit = ''
... |
def is_power2(num):
"""
states if a number is a power of two
"""
return num != 0 and ((num & (num - 1)) == 0) |
def insertion_sort(x):
"""Implementation of Selection sort.
Takes integer list as input,
returns sorted list.
"""
print("Starting insertion sort on list:\n", x)
iteration = 0
for i in range(1, (len(x))):
iteration += 1
print("Selection sort is in interation: ", iteration)
... |
def make_col_indicator(index):
"""Return a carrot indicator at index."""
return '{}^'.format(' ' * index) |
def revert(vocab, indices):
"""revert indices into words"""
ivocab = dict((v, k) for k, v in vocab.items())
return [ivocab.get(i, 'UNK') for i in indices] |
def pow__mod_c(a, k, c):
"""computes a^k (mod c),
we assume a,k>=1, c > 1 integers"""
if (k == 0):
return 1
elif (k & 1):
return ((a * pow__mod_c(a, k//2, c)**2) % c)
else:
return ((pow__mod_c(a, k//2, c)**2) % c) |
def get_extension(local_file: str) -> str:
"""Extract the file extension of a file."""
return local_file.rsplit(".", 1)[1].lower() |
def concat_dicts(list_of_dicts):
"""
Concatenate a list of dictionaries together into a single dictionary
"""
output_dict = list_of_dicts.pop(0)
for dictionary in list_of_dicts:
output_dict.update(dictionary)
return output_dict |
def prettify_seconds(seconds):
"""
Prettifies seconds.
Takes number of seconds (int) as input and returns a prettified string.
Example:
>>> prettify_seconds(342543)
'3 days, 23 hours, 9 minutes and 3 seconds'
"""
if seconds < 0:
raise ValueError("negative input not allowed")
... |
def get_jel_categories(s):
"""Return set of jel categories."""
cats = set()
try:
cats.update([j[0] for j in s["jel"] if j[0].isalpha()])
except TypeError:
pass
try:
cats.update([j[0] for j in s["jel3"] if j[0].isalpha()])
except TypeError:
pass
return list(cat... |
def peel_digits(num):
"""
Given a positive integer num, peel_digits returns a list filled with the digits
eg. given 1984, peel_digits returns the list [1, 9, 8, 4]
:param num: an integer to peel into a list of digits
:return: A list where each element of the list is a digit from num
"""
str_... |
def is_float(arg):
""" Returns True iff arg is a valid float """
if isinstance(arg, float) or isinstance(arg, int):
return True
try:
float(arg)
except ValueError:
return False
return True |
def v3_matrix_from_string(matrix_string):
"""Convert string-based rows of numbers to list of lists.
Turning everything into a list comprehension
"""
return [
[float(n) for n in row_string.split()]
for row_string in matrix_string.splitlines()
] |
def get_a_plus(chain_exon_class, aa_cesar_sat, aa_block_sat_chain, aa_ex_len):
"""Mark A+ exons as A+."""
chains = chain_exon_class.keys()
to_mark_a_p = []
for chain in chains:
c_exon_classes = chain_exon_class[chain]
c_cesar_sat = aa_cesar_sat[chain]
c_sat_chain = aa_block_sat_c... |
def read(filename):
"""Returns the file content as a string"""
f = open(filename)
content = f.read()
f.close()
return content |
def has_valueQ(remuneracao_dict):
"""
Return TRUE if 'remuneracao_dict' has a key like 'valor'.
Return FALSE otherwise.
"""
return any([s.lower().find('valor') != -1 for s in remuneracao_dict.keys()]) |
def generate(g, n):
"""Generate a (sub-)group using g as generator in modulus n"""
result = []
for i in range(1,n):
val = g ** i % n
if val != None and val > 0:
result.append(val)
if val < 2:
return result |
def expand_iupac(base: str, fill_n: bool=False) -> (str):
"""
Expand the IUPAC base
:param base: the IUPAC base to expand
:param fill_n: should we fill N or leave it empty
:return: a string with all the primary
bases that are encoded by the
IUPAC bases
"""
... |
def increase_by_one(liste, n):
"""
Parameters
----------
liste : list
n : int
Returns
-------
bool
True, if it can continue. False, if not.
"""
i = 1
liste[-i] += 1
while i <= len(liste) and liste[-i] == n:
liste[-i] = 0
i += 1
if (i == l... |
def get_default(arr, idx, default_value):
"""get arr[idx] or return default_value
"""
try:
return arr[idx]
except IndexError:
return default_value |
def format_pci_addr(pci_addr):
"""Pad a PCI address eg 0:0:1.1 becomes 0000:00:01.1
:param pci_addr: str
:return pci_addr: str
"""
domain, bus, slot_func = pci_addr.split(':')
slot, func = slot_func.split('.')
return '{}:{}:{}.{}'.format(domain.zfill(4), bus.zfill(2), slot.zfill(2),
... |
def check_symmetry_and_dim(number, dim=3):
"""
check if it is a valid number for the given symmetry
Args:
number: int
dim: 0, 1, 2, 3
"""
valid = True
msg = 'This is a valid group number'
numbers = [56, 75, 80, 230]
if dim not in [0, 1, 2, 3]:
msg = "invalid... |
def optimize_filter(vlan_filter, sep=","):
"""
Reorder and optimize vlan filter
:param vlan_filter:
:return:
"""
def get_part(v):
v = v.strip()
if "-" in v:
v1, v2 = [int(x) for x in v.split("-")]
return min(v1, v2), max(v1, v2)
else:
... |
def format_heading(level, text):
"""Create a heading of <level> [1, 2 or 3 supported]."""
underlining = {
0: '',
1: '=',
2: '-',
3: '~',
}
return '{}\n{}\n\n'.format(text, underlining[level] * len(text)) |
def get_raw_text(tag):
"""
:type tag: Tag
:rtype: NoneType or str
"""
if hasattr(tag, 'text'):
text = tag.text
if text is None:
return None
else:
text = str(tag)
return text |
def binarize_labels_nosaic_mnist(labels):
"""Change labels like even (class 0) vs odd (class 1) numbers
"""
labels = labels % 2
return labels |
def fis_zmf(x:float, a:float, b:float):
"""Z-shaped Member Function"""
m = ((a + b) / 2.0)
t = (b - a)
if x <= a:
return 1.0
if x <= m:
t = (x - a) / t
return (1.0 - (2.0 * t * t))
if x <= b:
t = (b - x) / t
return (1.0 - (2.0 * t * t))
return 0.0 |
def remove_border_spaces(string):
""" Strips the whitespace borders of a string.
Used inside 'read_config_file' function.
"""
if type(string) != str:
raise TypeError(
"Hey, a non-string object was passed to function "
"'Remove_border_spaces'!")
if string == '':
... |
def partition(l, pivot_index):
"""
Partitions a list at pivot index. Returns a tuple consisting of the
sublist before the partition, the pivot, and the sublist after the
pivot.
"""
return (l[:pivot_index], l[pivot_index], l[pivot_index + 1:]) |
def make_matrix(rows, cols, fill=0.0):
"""Returns a matrix (list of list of floats) using a default
value.
:param rows: Number of rows
:type rows: int
:param cols: Number of columns
:type cols: int
:param fill: Default value for each element in the matrix
:type fill: float
"""
m... |
def align_to_next(number, alignment):
"""Returns number if number % alignment is 0 or returns the next
number such that number % alignment is 0"""
if number % alignment == 0:
return number
return number + alignment - (number % alignment) |
def interpolate(x0, y0, x1, y1, x):
"""Linear interpolation between two values.
"""
try:
y = (y0 * (x1 - x) + y1 * (x - x0)) / (x1 - x0)
except ZeroDivisionError as e:
print(x1,x0)
raise e
return y |
def parse_request(func):
"""
get json spec
"""
data = {}
if hasattr(func, 'json'):
data = {
'content': {
'application/json': {
'schema': {
'$ref': f'#/components/schemas/{func.json}'
}
... |
def _display_result(field, result):
"""Accept a field name and a validation result pair
Display an error if it exists
"""
okay, error = result
return '' if okay else error(field) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.