content stringlengths 42 6.51k |
|---|
def ensure_all_alt_ids_have_a_nest(nest_spec, list_elements, all_ids):
"""
Ensures that the alternative id's in `nest_spec` are all associated with
a nest. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
Keys are strings tha... |
def BCD_calc(TOP, P, AM):
"""
Calculate Bray-Curtis dissimilarity (BCD).
:param TOP: number of positives in predict vector
:type TOP: dict
:param P: number of actual positives
:type P: dict
:param AM: Automatic/Manual
:type AM: int
:return: BCD as float
"""
try:
TOP_... |
def convert_int_list_to_range_lists(int_list, *, sort_list=True):
"""
Convert a list of numbers to ranges and returns a list of tuples representing the ranges.
Single numbers will be represented as (3, 3), while ranges will be (4, 8)
"""
# Build a list of lists
range_list = []
working_list ... |
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if name and name[0] != '<' and name[-1] != '>':
return name |
def pprint_formatter(data, **kwargs):
"""Method to pprint format results"""
from pprint import pformat
return pformat(data, indent=4) |
def get_depth(count):
""" returns the depth of the tree
- count -- 32 bit value
eg: If any number between 9 and 16 is passed the function returns 4
"""
l = count
depth = 0
l = l>> 1
while l != 0:
depth = depth + 1
l = l>> 1
#more than one 1s in t... |
def label2action(label):
""" Transform label to action
"""
items = label.split('-')
if len(items) == 1:
action = (items[0], None, None)
elif len(items) == 3:
action = tuple(items)
else:
raise ValueError("Unrecognized label: {}".format(label))
return action |
def connection_type_validator(type):
"""
Property: ConnectionInput.ConnectionType
"""
valid_types = [
"CUSTOM",
"JDBC",
"KAFKA",
"MARKETPLACE",
"MONGODB",
"NETWORK",
"SFTP",
]
if type not in valid_types:
raise ValueError("% is not a... |
def max_modified_date(obj, modified):
"""
Return the largest modified date
If the object does not have a date_modified the argument is returned
:param obj:
:param modified:
:return:
"""
if 'date_modified' not in obj or int(obj['date_modified']) < int(modified):
return modified
... |
def get_frequency_dictionary(data):
"""
Takes a string or list of strings and returns a dictionary of unique
members and their abundance. Similar to itertools.Counter.
"""
return {k: data.count(k) for k in set(data)} |
def cmp(x, y):
"""
The 3-way comparison function as a pseudo-global.
x < y --> returns a negative number
x == y --> returns 0
x > y --> returns a positive number
Though not officially part of the ordinal API,
it is so important for performance here
that we justify making it publicly a... |
def all_equal(iterable):
"""Return True if all elements in `iterable` are equal.
Also returns True if iterable is empty.
"""
iterator = iter(iterable)
try:
first = next(iterator)
except StopIteration:
return True # vacuously True
return all(element == first for element in ... |
def make_disjoint_window(pair):
""" Takes output from get_rolling_token_windows and makes the context not overlap with the continuation """
a, b = pair
return a[:-(len(b) - 1)], b |
def filter_colour(x):
"""returns a colour used to fill-in buttons associated with specific
filters - ensures consistency across views and templates.
"""
button_colours = {
"agency": "red",
"lake": "blue",
"year": "teal",
"first_year": "green",
"last_year": "oliv... |
def has_snapshot_with_keys(snapshots, keys):
""" Test if a snapshot with the given subset of keys exists """
return any( set(keys).issubset(set(s.keys())) for s in snapshots ) |
def shorten_text(text: str, length: int) -> str:
"""
Shorten text to length chars cut to last space or new line and add '...'
:param text: Text to be shortened
:type text: str
:param length: Maximum text length after cut, not counting '...'
:type length: int
:return: Shortened text
:rtyp... |
def multiples35(number):
"""
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
multiples is 23. Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number
passed in. Note: If the number is a multiple of bo... |
def _to_cli_args(opts:dict):
"""
convert dict to cli options for HM & VTM softwares
"""
args = []
for k, v in opts.items():
if k.startswith('--'):
args.append(f'{k}={v}')
else:
args += [k, str(v)]
return args |
def calculate_steps(time):
"""
Function to calculate the amount of steps for each trayectory.
"""
return int(time * 100) |
def BuildKeyList(Dictionary):
"""
WARNING: This function is for internal use.
Return a list of lists where each inner list is chain of valid keys which when input access the dictionary tree and retrieve a numerical sample.
"""
if isinstance(Dictionary, dict):
Result = []
for Key in D... |
def list_all_children(function, child_field, *args, **kwargs):
"""
Given a standard AWS boto list_* function this will return all the child
objects taking possible paging into account.
"""
def innerFn():
first_response = function(*args, **kwargs)
for child in first_response[child_fi... |
def py2(h, kr, rho, cp, r):
"""
Calculate the pyrolysis number.
Parameters
----------
h = heat transfer coefficient, W/m^2K
kr = rate constant, 1/s
rho = density, kg/m^3
cp = heat capacity, J/kgK
r = radius, m
Returns
-------
py = pyrolysis number, -
"""
py = h ... |
def compute_size(requested_width, requested_height, rev_width, time_height):
"""Converts potentially empty requested size into a concrete size.
(Number?, Number?) -> (Number, Number)"""
pic_width = 0
pic_height = 0
if (requested_width is not None and requested_height is not None):
pic_... |
def spin_stat_factor(J,I):
"""
The spin statistical factor
The spin statistical factor is the probability that
a particular compound state will form for a given J
and I when neutrons interact with the nucleus.
Parameters
----------
J : float or array-like
J is the compound... |
def _pick_channels_spatial_filter(ch_names, filters):
"""Return data channel indices to be used with spatial filter.
Unlike ``pick_channels``, this respects the order of ch_names.
"""
sel = []
# first check for channel discrepancies between filter and data:
for ch_name in filters['ch_names']:
... |
def github_site_admin_user_promotion(rec):
"""
author: @fusionrace, @mimeframe
description: Alert when a Github Enterprise user account is promoted to a
Site Administrator (privileged account)
reference: https://help.github.com/enterprise/2.11/admin/guides/
... |
def exp_limit(x, iterations=8):
"""Approximates the exponential function using a limit approximation:
exp(x) = \lim_{n -> infty} (1 + x / n) ^ n
Here we compute exp by choosing n = 2 ** d for some large d equal to
iterations. We then compute (1 + x / n) once and square `d` times.
Args:
ite... |
def determineLineEnding(text):
"""Get the line ending style used in the text.
\n, \r, \r\n,
The EOLmode is determined by counting the occurrences of each
line ending...
"""
text = text[:32768] # Limit search for large files
# test line ending by counting the occurrence of each
c_win = ... |
def row_text(rendered_row):
"""Return all text joined together from the rendered row
"""
return b"".join(x[-1] for x in rendered_row) |
def tcl_findprd_prepcuref(center, tail, noprefix=False, key2mode=False):
"""
Prepare candidate PRD.
:param center: PRD-center-tail.
:type center: str
:param tail: PRD-center-tail.
:type tail: int
:param noprefix: Whether to skip adding "PRD-" prefix. Default is False.
:type noprefix: ... |
def _control_indices_in_nested_list(nested_list, control):
"""Given a nested list (QuTiP Hamiltonian), find the indices that contain
`control` and return them as a list"""
result = []
for i, item in enumerate(nested_list):
if isinstance(item, list):
assert len(item) == 2
... |
def extract_dictionary_element(line):
"""Extract a dictionary element from the given string."""
# An element should start and end with a double-quote.
start_index = line.find('"')
end_index = line.rfind('"')
if start_index == -1 or end_index == -1 or start_index == end_index:
return None
element = line... |
def iso_string_to_sql_utcdate_mysql(x: str) -> str:
"""
Provides MySQL SQL to convert an ISO-8601-format string (with punctuation)
to a ``DATE`` in UTC. The argument ``x`` is the SQL expression to be
converted (such as a column name).
"""
return (
f"DATE(CONVERT_TZ(STR_TO_DATE(LEFT({x}, ... |
def split_region(region):
"""
Returns the municipality and the province
"""
if region.find(", ") > 0:
return tuple(region.rsplit(", "))
else:
return None, region |
def normalize_slice(s, total):
"""
Return a "canonical" version of slice ``s``.
:param slice s: the original slice expression
:param total int: total number of elements in the collection sliced by ``s``
:return slice: a slice equivalent to ``s`` but not containing any negative indices or Nones.
... |
def subject_labels_in_range(start: int, stop: int) -> list:
"""Returns a list of labels for subjects in the subject column.
:param start: integer between 2 and 57, inclusive.
:param stop: integer between 2 and 57, inclusive. Should be greater than or
equal to start.
:returns: list of z... |
def cleanObjectProperties(props):
"""Cleans a predefined list of Blender-specific or other properties from the dictionary.
Args:
props:
Returns:
"""
getridof = [
'phobostype',
'_RNA_UI',
'cycles_visibility',
'startChain',
'endChain',
'masscha... |
def data_bits(n: int = 2):
"""
Calculate the data bits in one hamming data block.
:param n: The dimension of the hamming data block is specified by 2 ** n or n << 1
:return: The number of valid data bits carrying information in one hamming data block.
"""
return (1 << 2 * n) - (n << 1) - 1 |
def ordered(x1,x2,x3):
"""
given collinear points, return true if they are in order
along that line
"""
if x1[0]!=x2[0]:
i=0
else:
i=1
return (x1[i]<x2[i]) == (x2[i]<x3[i]) |
def merge(novel_adj_dict, full_adj_dict):
"""
Merges adjective occurrence results from a single novel with results for each novel.
:param novel_adj_dict: dictionary of adjectives/#occurrences for one novel
:param full_adj_dict: dictionary of adjectives/#occurrences for multiple novels
:return: full_... |
def harmonic_mean(frequencies1, frequencies2):
"""Finds the harmonic mean of the absolute differences between two frequency profiles,
expressed as dictionaries.
Assumes every key in frequencies1 is also in frequencies2
>>> harmonic_mean({'a':2, 'b':2, 'c':2}, {'a':1, 'b':1, 'c':1})
1.0
>>> har... |
def contains_here(message: str):
""" Checks if a string contains @here or similar words """
target = {'@here', 'here', 'online'}
message_split = set(message.split())
return len(target & message_split) > 0 |
def check_no_need_or_result(content):
"""
Little method used when the len of content equals 2.
If the lenght isn't 3 it means that we are missing something,
either needs or result.
Here we just determine if the need or result is missing
"""
if content.count(':') == 2:
return 'result'... |
def get_chunk_size(num_elements: int, min_chunk_size: int) -> int:
"""Adjust chunk_size to minimize imbalance between chunk sizes"""
if min_chunk_size >= num_elements:
return min_chunk_size
leftover_elements = num_elements % min_chunk_size
num_chunks = num_elements // min_chunk_size
return m... |
def split_count_helper(data, split_count):
"""Helper to override the split count if data len is shorter"""
if hasattr(data, "__len__"):
return min(len(data), split_count)
return split_count |
def is_list_of_tuples(lst):
"""
check is a object if of the type list of tuples
"""
return bool(lst) and isinstance(lst, list) and \
all(isinstance(elem, tuple) for elem in lst) |
def _files(*paths):
"""Files for PyDoIt (It doesn't allow pathlib2, only str or pathlib)."""
return [str(x) for x in paths] |
def information_coefficient(total1, total2, intersect):
"""a simple jacaard (information coefficient) to compare two lists of overlaps/diffs"""
total = total1 + total2
return 2.0 * intersect / total |
def find_increment(states, modulus, multiplier):
"""
give states, modulus & multiplier, recover the increment
s1 = s0*m + c
c = s1 - s0*m
"""
increment = (states[1] - states[0]*multiplier) % modulus
return multiplier, increment, modulus |
def mergeTypeAndVariable(type, variable):
"""
Combines type and variable to a single line of code.
"""
dimension = ""
type = type.strip()
while type.endswith(']'):
index = type.rfind('[')
dimension = type[index:] + dimension
type = type[:index]
return "{} {}{}". forma... |
def get_no_impact_logic(context_str):
"""Get the silent tag from context
return silence value and context value"""
value = {
'YES:NOIMPACT': (True, 'YES'),
'YES': (False, 'YES'),
'Y:NOIMPACT': (True, 'YES'),
'Y': (False, 'YES'),
'NO:NOIMPACT': (True, 'No'),
'N... |
def add_slash(path):
"""
Ensure that the path ends with a slash
"""
if not path.endswith('/'):
return path + '/'
return path |
def bounds_check(i):
"""
Verify that values remain in valid range
"""
if i >= 255:
return 255
elif i < 0:
return 0
else:
return i |
def find_point_columns(datatype_map):
"""
parses through datatype_map and outputs array containing all columns of
data type Point
"""
point_columns = [
col for col, col_type in datatype_map.items() if col_type == "POINT"
]
return point_columns |
def save_figures_to_pngs(figures_filenames):
"""
List of pairs (figure, filename) to png figures
"""
for fig, filename in figures_filenames:
fig.savefig(filename)
return None |
def remove_dot_segments(path):
"""
Supports absolutize() by implementing the remove_dot_segments function
described in RFC 3986 sec. 5.2. It collapses most of the '.' and '..'
segments out of a path without eliminating empty segments. It is intended
to be used during the path merging process and ma... |
def get_topic_name(num_partitions, msg_size_bytes):
"""Generate test-topic names describing message characteristics"""
return "parts{}-size{}".format(num_partitions, msg_size_bytes) |
def check_empty_fields(values:dict)->bool:
"""Chequea que no haya campos vacios
Args:
values (dict): valores de la ventana, de donde obtenemos los valores a chequear
Returns:
[boolean]: Si hay campos vacios o no
"""
nonempty_values = [
values["-VICTORY TEXT-"],
val... |
def is_unicode(data_b):
"""
data_b is a bytes object.
"""
try:
data_b.decode()
return True
except UnicodeDecodeError:
return False |
def find_paths(diffs):
"""
When chargers are 3 units apart, there's only one path
between them.
When they are 1 units apart, there are multiple paths
between them, depending on the run of the 1-unit differences:
If only 1 such difference, there's one path. If 2 there's 2,
if 3, there's 4...... |
def get_max(input_number):
"""
Get the max value in input_numebr list.
Arguments:
input_number -- a list contain all the numbers of user's input
Returns:
max_value -- the max value in input_numebr list.
"""
max = float('-inf')
for i in input_number:
max = i if i > m... |
def _get_package_status(package):
"""Get the status for a package."""
status = package["status_str"] or "Unknown"
stage = package["stage_str"] or "Unknown"
if stage == "Fully Synchronised":
return status
return "%(status)s / %(stage)s" % {"status": status, "stage": stage} |
def temkin_pyzhev_rate(concentrations, para_dict):
"""Rate expression for ammonia chemsitry from Temkin and Pyzhev
"""
rate = para_dict['k1']*concentrations[0]*(concentrations[1]**3/concentrations[0]**2)**para_dict['alpha'] -\
para_dict['k2']*(concentrations[2]**2/concentrations[1]**3)**para_dict['b... |
def mph(mps):
"""
Meters per second to miles per hour
"""
mpsToMph = 3600.0 / (0.0254 * 12.0 * 5280.0)
return mps * mpsToMph |
def rreplace(string, old, new, occurrence=1):
"""
Replace n occurrences of old in string with new, starting from the end.
"""
parts = string.rsplit(old, occurrence)
return new.join(parts) |
def get_viable_disks(space_needed, maximum, sorted_available):
"""Get number of disks that can fit at least space_needed."""
disks_num = -1
while space_needed <= maximum and disks_num == -1:
try:
disks_num = sorted_available.index(space_needed)
except ValueError:
spac... |
def nh_linear(dist, r):
"""neighbourhood function that is linearly decline to 0 within r"""
return dist / r if dist <= r and r > 0 else 0 |
def ex_cant_create():
"""Can't create response error in bytes."""
return b"SPAMD/1.5 73 EX_CANTCREAT\r\n\r\n" |
def convert_to_demisto_severity(severity: str) -> int:
"""Maps Cognni severity to Cortex XSOAR severity
Converts the Cognni alert severity level ('Low', 'Medium',
'High', 'Critical') to Cortex XSOAR incident severity (1 to 4)
for mapping.
:type severity: ``str``
:param severity: severity as re... |
def is_tree_node(node):
"""Returns True if the given node is a tree node."""
return getattr(node, "_node_type", None) == "tree" |
def set_bit(number: int, position: int, value: bool) -> int:
"""
Returns number if you were to set the nth bit to "value".
0 refers to the LSB, aka 1s place.
"""
return (
(number | (1 << position)) if value else
(number & ~(1 << position))
) |
def apply(f, xs):
"""Applies function fn to the argument list args. This is useful for
creating a fixed-arity function from a variadic function. fn should be a
bound function if context is significant"""
return f(*xs) |
def new_lines_replaser(string):
""" string clean up function for language-tool server """
string = string.replace(' \n', ' ').replace('\n ', ' ')
return string.replace('\n', ' ').replace(' ', ' ') |
def _split_first(s, sub):
"""Splits string `s` at the first occurrence of substring `sub` and returns
a tuple of the form (left, right)."""
return (s.split(sub)[0], sub.join(s.split(sub)[1:])) |
def get_num_channels(features, sequence_length = 1):
"""Returns the number of channels."""
if sequence_length == 1:
return len(features)
return len(features) // sequence_length |
def convert_prices(price):
"""Convert price string to int."""
return int(price.replace("$", "").replace(",", "")) |
def _str_val(obj):
"""Returns the value of obj as a string. If obj is not a string (constant
symbol), it must be a Symbol."""
return obj if isinstance(obj, str) else obj.get_value() |
def _append_results(group, step, step_results, results):
"""
Adds results from each simulation steps to temporary results dictionary
"""
results_keys = results.keys()
step_results_keys = step_results.keys()
for key in step_results_keys:
variable = group + '_' + key
if variable ... |
def _compute_birthday_problem_probability(d, lower_bound_probability=0.1):
"""
Suppose we draw N samples and all are distinct values. We can compute the probability of this event happening
(N unique values in N draws) for specific R number of distinct values within a population, this helps us put a
... |
def path_to_glob(path):
"""
Convert pattern style paths to glob style paths
Returns path if path is not str
Parameters
----------
path : str
Path to data optionally containing format_strings
Returns
-------
glob : str
Path with any format strings replaced with *
... |
def maybe_float(string_or_none):
"""
Parse a string into a float, or None.
"""
if string_or_none in {None, ""}:
return None
return float(string_or_none) |
def motif2regex(motif):
"""Converts a protein motif query to a regex search"""
return motif.replace('X', '.').replace('x', '.').replace('(', '{').replace(')', '}') |
def is_candidate_word(word):
"""
check a word is correct candidate word for identifying pronoun
"""
discarded_words = ["a", "an", "the"] # can enhance this list
if len(word)<=2 or word.lower() in discarded_words:
return False
return True |
def get_index_str(idxs, discard, cap, header=None):
"""Returns str of indexes to save to file
"""
if header is None:
header = 'Indexes of samples from mcmc chain ' \
f'(after slicing: discard={discard}, cap={cap})'
string = f'{header}\n'
for i in idxs:
string += f'{... |
def size_format(value):
"""Jinja filter to format the binary size"""
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
i = 0
nbytes = int(value) if f"{value}".isdigit() else 0
while nbytes >= 1024 and i < len(suffixes)-1:
nbytes /= 1024
i += 1
fsize = ('%.1f' % nbytes).rstrip('0').r... |
def order_by(sequence, *sort_order):
"""Sort a sequence by multiple criteria.
Accepts a sequence and 0 or more (key, reverse) tuples, where
the key is a callable used to extract the value to sort on
from the input sequence, and reverse is a boolean dictating if
this value is sorted in ascending or ... |
def div_by(n, list_of_num):
"""Validates if a number is divisible by any number of a list"""
for num in list_of_num:
if not n % num:
return True
return False |
def str2bool(string: str) -> bool:
"""
:param string: e.g. "True"
:return: bool type
"""
string = string.lower()
if string == 'true':
return True
else:
return False |
def action2cord(a):
"""
input : action 0~7
output : x ,y changes
"""
# return {'0':[0,-1],'1':[0,1],'2':[1,0],'3':[-1,0],'4':[1,-1],'5':[-1,-1],'6':[1,1],'7':[-1,1]}.get(str(a),[0,0])
return {'0':[-1,0],'1':[1,0],'2':[0,1],'3':[0,-1],'4':[-1,1],'5':[-1,-1],'6':[1,1],'7':[1,-1]}.get(str(a),[0,0]) |
def Slide_hasCode(cont_Bullets_hasCode, cont_Code_center, cont_Verbatim_center, cont_Column_hasCode):
"""
:param cont_Bullets_hasCode: The sequence of "hasCode" values of Bullets objects contained in this Slide
:type cont_Bullets_hasCode: Array
:param cont_Code_center: The sequence of Code objects cont... |
def assert_list(obj):
"""Make sure it is a list"""
try:
# isinstance(obj, list) and not isinstance(obj, str)
if getattr(obj, 'append') and getattr(obj, 'sort') and getattr(obj, 'pop'):
return True
except:
return False |
def replace_positions(st_coords, end_coords):
"""Replace the order of positions, if needed"""
if end_coords < st_coords: # end smaller than start
return str(end_coords), str(st_coords) # replace
# return end_coords, st_coords # replace
return str(st_coords), str(end_coords) |
def normalize(data: dict):
"""
:param data: dict[str, list], key is the column name, value is its data
:return data: dict[str, list], key is the column name, value is its normalized data
"""
for name in data:
nor_value = []
for value in data[name]:
if value-min(data[name]) == 0 or max(data[name])-min(data[n... |
def linear_search(array, item):
"""Returns true if item is in array
Time Complexity O(n)
"""
for i in range(len(array)):
if array[i] == item:
return True
return False |
def non_unicode_kwarg_keys(kwargs):
"""Convert all the keys to strings as Python won't accept unicode.
"""
return dict([(str(k), v) for k, v in kwargs.items()]) if kwargs else {} |
def yields_from_mori_2018_w7(feh):
"""
Supernova data source: Mori, K. et al., 2018, The Astrophysical Journal, 863:176 W7
"""
return [0.0, 4.794e-2, 4.150e-8, 5.809e-6, 1.356e-1, 1.309e-3, 1.026e-2, 1.732e-1, 7.890e-2, 1.133e-2, 6.683e-1] |
def compute_mean_reciprocal_rank_for_single_sample(real_gains, predicted_gains):
"""Given real gains and predicted gains, computes the mean reciprocal rank (MRR) between them.
Ideally, this metric should be used over large lists (multiple samples) of real gains and
predicted gains
"""
real_ranking ... |
def iv_put(s: float, k: float) -> float:
"""Intrinsic value of a put"""
return max([0, k - s]) |
def index_max(x):
"""
:param x: vector whose max index has to be returned
:return: index of the max element in x
"""
m = max(x)
return x.index(m) |
def squares(num_list):
"""assumes num_list is a list of numerics
returns a list of squares of each elem of num_list"""
square_list = []
for num in num_list:
square = num**2
square_list.append(square)
return square_list |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.