content stringlengths 42 6.51k |
|---|
def compute_perc_word_usage(word, tokenized_string):
"""
Given a tokenized string (list of tokens), return the fraction of use of a given word as fraction of all tokens.
"""
return tokenized_string.count(word) / len(tokenized_string) |
def d8flowdir(np, input, output1, output2):
""" command: d8flowdir -fel demfel.tif -p demp.tif -sd8 demsd8.tif, demfile: Pit filled elevation input data, pointfile: D8 flow directions output, slopefile: D8 slopes output """
d8flowdir = "mpirun -np {} d8flowdir -fel {} -p {} -sd8 {}".format(
np, input, output1, output2)
return d8flowdir |
def mk_and_expr(expr1, expr2):
"""
returns an and expression
of the form (EXPR1 /\ EXPR2)
where EXPR1 and EXPR2 are expressions
"""
return {"type": "and",
"expr1": expr1,
"expr2": expr2} |
def _group_proteins(proteins, peptides):
"""Group proteins when one's peptides are a subset of another's.
WARNING: This function directly modifies `peptides` for the sake of
memory.
Parameters
----------
proteins : dict[str, set of str]
A map of proteins to their peptides
peptides : dict[str, set of str]
A map of peptides to their proteins
Returns
-------
protein groups : dict[str, set of str]
A map of protein groups to their peptides
peptides : dict[str, set of str]
A map of peptides to their protein groups.
"""
grouped = {}
for prot, peps in sorted(proteins.items(), key=lambda x: -len(x[1])):
if not grouped:
grouped[prot] = peps
continue
matches = set.intersection(*[peptides[p] for p in peps])
matches = [m for m in matches if m in grouped.keys()]
# If the entry is unique:
if not matches:
grouped[prot] = peps
continue
# Create new entries from subsets:
for match in matches:
new_prot = ", ".join([match, prot])
# Update grouped proteins:
grouped[new_prot] = grouped.pop(match)
# Update peptides:
for pep in grouped[new_prot]:
peptides[pep].remove(match)
if prot in peptides[pep]:
peptides[pep].remove(prot)
peptides[pep].add(new_prot)
return grouped, peptides |
def _apply_to_sample(func, sample, *args, nest_with_sample=0):
"""Apply to a sample traversing the nesting of the data (tuple/list).
Parameters
----------
func : callable
Function to be applied to every sample data object
sample : sample object or any nesting of those in tuple/list
Representation of sample
nest_with_sample: int
Specify how many consecutive (additional) arguments have the same level of nesting
as the sample.
"""
if isinstance(sample, (tuple, list,)):
# Check that all the samples have common nesting
for i in range(nest_with_sample):
assert len(args[i]) == len(sample)
nest_group = sample, *args[0:nest_with_sample]
scalar_args = args[nest_with_sample:]
return type(sample)(_apply_to_sample(func, *part, *scalar_args) for part in zip(*nest_group))
else:
# we unpacked all nesting levels, now is actual data:
return func(sample, *args) |
def d_index_no_except(seq, obj, i=None, j=None):
"""
Provides a no-exception wrapper for indexing sequence types. With
the exception of the first parameter, the interface for the sequence
`index` function is equivalent.
:param seq
The sequence object to index.
:param obj
The object whose index to retrieve.
:param i
The inclusive starting index of the search.
:param j
The exclusive ending index of the search.
"""
try:
if i is not None:
if j is not None:
return seq.index(obj, i=i, j=j)
else:
return seq.index(obj, i=i)
else:
return seq.index(obj)
except ValueError:
return -1 |
def get_purchase_cost(units):
"""Return the total equipment purchase cost of all units in million USD."""
return sum([i.purchase_cost for i in units]) / 1e6 |
def build_url(ip, port, path=""):
"""
:param ip:
:param port:
:param path:
:return:
>>> build_url("localhost", 8081)
'http://localhost:8081/'
>>> build_url("localhost", 8081, 'api/v1/apprecord')
'http://localhost:8081/api/v1/apprecord'
"""
return "http://{}:{}/{}".format(ip, port, path) |
def lower_and_add_dot(s):
"""
lower_and_add_dot(s)
Returns the given string in all lowercase and adds a . to the beginning
if there was not already one.
"""
if s[0] != '.':
return '.' + s.lower()
else:
return s.lower() |
def should_serve_drinks(age: int, on_break: bool) -> bool:
"""Serve drinks based on age and break."""
return (age >= 18) and not(on_break) |
def get_m3(m1, c, gamma):
"""
Helper: get M3 value from M1, Cv and skewness.
"""
std = c * m1
var = std**2
return gamma * var * std + 3 * m1 * var + m1**3 |
def column_selection(names, columns):
"""
select the columns that contain any of the value of names
Args:
names (TYPE): DESCRIPTION.
columns (TYPE): DESCRIPTION.
Returns:
features (TYPE): DESCRIPTION.
"""
features = []
for col in columns:
if any([name in col for name in names]):
features.append(col)
return features |
def solution(A): # O(N/2)
"""
Write a sorting function to put the even numbers first, odd numbers afterwards.
>>> solution([5, 2, 2, 4, 1, 3, 7, 9])
[4, 2, 2, 5, 1, 3, 7, 9]
>>> solution([2, 4, 6, 2, 0, 8])
[2, 4, 6, 2, 0, 8]
>>> solution([1, 3, 5, 7, 3, 9, 1, 5])
[1, 3, 5, 7, 3, 9, 1, 5]
"""
i = 0 # O(1)
j = len(A) - 1 # O(1)
def is_even(value):
return value % 2 == 0 # O(1)
def is_odd(value):
return value % 2 == 1 # O(1)
while i < j: # O(N/2)
if is_even(A[i]): # O(1)
i += 1 # O(1)
if is_odd(A[j]): # O(1)
j -= 1 # O(1)
if is_odd(A[i]) and is_even(A[j]): # O(1)
A[i], A[j] = A[j], A[i] # O(1)
i += 1 # O(1)
j -= 1 # O(1)
return A # O(1) |
def all_equal(seq):
"""Checks if all elements in `seq` are equal."""
seq = list(seq)
return not seq or seq.count(seq[0]) == len(seq) |
def _phi0_dd(tau,dta):
"""Calculate fluid water potential ideal term DD-derivative.
Calculate the second derivative of the ideal gas component of the
Helmholtz potential (scaled free energy) for fluid water with
respect to reduced density.
:arg float tau: Reduced temperature _TCP/temp(K).
:arg float dta: Reduced density dflu(kg/m3)/_DCP.
:returns: Helmholtz potential derivative, unitless.
"""
return -dta**-2 |
def get_node_level(line) -> int:
"""Get the node level of a line, returning 0 if the line doesn't define a node."""
if line.strip().startswith("*"):
return len(line.strip().split(" ")[0])
else:
return 0 |
def remove_special_characters(data):
"""
this may need to be more sophistacated than below...
"""
data = data.replace("-", " ")
data = data.replace("'", "")
data = data.replace("`", "")
return data |
def missingNumberB(nums):
"""
:type nums: List[int]
:rtype: int
"""
expected_sum = len(nums)*(len(nums)+1)//2
actual_sum = sum(nums)
return expected_sum - actual_sum |
def cbond(
_dir="->",
angle=0,
coeff=1.2,
n1="",
n2=""
) -> str:
"""func cbond
Return the code for a coordinate/dative bond
Args:
_dir : Direction of the arrow
angle: Angle from baseline
coeff: Bond length multiplier
n1/n2: Atom identifiers
Returns:
A string with the list of all this stuff.
"""
# bond = []
# for param in params:
# if param
# arrow = "->"
return f"[{angle},{coeff},{n1},{n2},{_dir}]" |
def hex2rgb(h):
"""Convert Hex color encoding to RGB color"""
h = h.lstrip("#")
return tuple(int(h[i : i + 2], 16) for i in (0, 2, 4)) |
def qubit_from_push(g, bare_res, pushed_res):
"""
Get estimated qubit location given coupling, push on resonator
and bare resonator position.
Args:
g: coupling in Hz
bare_res: high power resonator position in Hz
pushed_res: low power resonator position in Hz
Returns:
estimated qubit frequency
"""
push = pushed_res - bare_res
delta = g**2 / push
return bare_res - delta |
def IoU(rect1, rect2):
""" Calculates IoU of two rectangles.
Assumes rectanles are in ltrb (left, right, top, bottom) format.
ltrb is also known as x1y1x2y2 format, whch is two corners
"""
intersection = max( min(rect1[2], rect2[2]) - max(rect1[0], rect2[0]), 0 ) * \
max( min(rect1[3], rect2[3]) - max(rect1[1], rect2[1]), 0 )
# A1 + A2 - I
union = (rect1[2] - rect1[0]) * (rect1[3] - rect1[1]) + \
(rect2[2] - rect2[0]) * (rect2[3] - rect2[1]) - \
intersection
return float(intersection) / max(union, .00001) |
def create_local_meta(name):
"""
Create the metadata dictionary for this level of execution.
Parameters
----------
name : str
String to describe the current level of execution.
Returns
-------
dict
Dictionary containing the metadata.
"""
local_meta = {
'name': name,
'timestamp': None,
'success': 1,
'msg': '',
}
return local_meta |
def parse_int(data_obj, factor=1):
"""convert bytes (as signed integer) and factor to float"""
decimal_places = -int(f'{factor:e}'.split('e')[-1])
return round(int.from_bytes(data_obj, "little", signed=True) * factor, decimal_places) |
def create_zero_sales_email_text(vendor_firstname, date_start, date_end, email):
"""
Create full text of an email tailored to the details of the vendor and reporting period
when the vendor made no sales for the reporting period.
Parameters
-------
vendor_firstname : str
First name of the vendor receiving the email.
date_start : str
String representation of the first date of the reporting period.
date_end : str
String representation of the last date of the reporting period.
email : str
Message recipient's email address.
Returns
-------
text : str
Full text of email populated with vendor and payment variables for a tailored message.
"""
text = f'''Hi {vendor_firstname}!\n
I am sorry to say that you didn't have any sales at The Beverly Collective for the period of {date_start} through {date_end}.\n
Thank you, and I hope you are having a great week!\n
Best,
Monica'''
return text |
def circumferenceofcircle(r):
"""
calculates circumference of circle
input:radius of circle
output:circumference of circle
"""
PI = 3.14159265358
cmf = PI*2*r
return cmf |
def proportion(number_list):
"""Return the proportion of correct truncation prediction.
Parameters
----------
number_list : list of int
Returns
-------
float
"""
return number_list.count(0) / len(number_list) |
def transform_s1zs2z_chi_eff_chi_a(mass1, mass2, spin1z, spin2z):
#Copied from pycbc https://github.com/gwastro/pycbc/blob/master/pycbc/conversions.py
""" Returns the aligned mass-weighted spin difference from mass1, mass2,
spin1z, and spin2z.
"""
chi_eff = (spin1z * mass1 + spin2z * mass2) / (mass1 + mass2)
chi_a = (spin2z * mass2 - spin1z * mass1) / (mass2 + mass1)
return chi_eff,chi_a |
def get_closest(items, pivot):
"""
Return the item in the list of items closest to the given pivot.
Items should be given in tuple form (ID, value (to compare))
Intended primarily for use with datetime objects.
See: S.O. 32237862
"""
return min(items, key=lambda x: abs(x[1] - pivot)) |
def db2lin(val):
"""
Converting from linear to dB domain.
Parameters
----------
val : numpy.ndarray
Values in dB domain.
Returns
-------
val : numpy.ndarray
Values in linear domain.
"""
return 10 ** (val / 10.) |
def create_first_n_1_bits_mask(n, k):
""" Return a binary mask of first n bits of 1, k bits of 0s"""
if n < 0 or k < 0:
raise ValueError("n and k cannot be negative number")
if n == 0:
return 0
mask = (2 << n) - 1
return mask << k |
def cmdline_options(argv: list, arg_dict: dict):
"""
Parse command line arguments passed via 'argv'.
:param argv: The list of command-line arguments as produced by sys.argv
:param arg_dict: Dictionary of valid command-line argument entries of type {str: bool}.
:return: arg_dict with args specified in argv True and unspecified args False
"""
if len(argv) > 1:
# Loop through options - skipping item 0 which is the name of the script
for arg in argv[1:]:
# Indicate which expected args that have been passed
if arg in arg_dict:
arg_dict[arg] = True
return arg_dict |
def get_int_or_none(value):
"""
If value is a string, tries to turn it into an int.
"""
if type(value) is str:
return int(value)
else:
return value |
def mdhtmlEsc(val):
"""Escape certain Markdown characters by HTML entities or span elements.
To prevent them to be interpreted as Markdown
in cases where you need them literally.
"""
return (
""
if val is None
else (
str(val)
.replace("&", "&")
.replace("<", "<")
.replace("|", "|")
.replace("$", "<span>$</span>")
)
) |
def calc_pad(pad, in_siz, out_siz, stride, ksize):
"""Calculate padding width.
Args:
pad: padding method, "SAME", "VALID", or manually speicified.
ksize: kernel size [I, J].
Returns:
pad_: Actual padding width.
"""
if pad == 'SAME':
return max((out_siz - 1) * stride + ksize - in_siz, 0)
elif pad == 'VALID':
return 0
else:
return pad |
def mat_dims_equal(a, b, full_check=False):
"""
Checks whether two matrices have equal dimensions
Parameters
----------
a: list[list]
A matrix
b: list[list]
A matrix
full_check: bool, optional
If False (default) then the check on the second dimension (number
of columns) is done on the first rows only, that is a[0]==b[0] and
it's assumed that all the others have the same size. If True then
all the rows are compared.
Returns
-------
bool
True if the two matrices have equal dimensions, False otherwise.
"""
if not full_check:
return len(a) == len(b) and len(a[0]) == len(b[0])
else:
return len(a) == len(b) and all(
map(lambda r1, r2: len(r1) == len(r2), a, b))
# if not len(a) == len(b):
# return False
# cols_equal = True
# for n in range(len(a)):
# cols_equal &= len(a[n]) == len(b[n])
# return cols_equal |
def _relabel_nodes_in_edges(edges, idx):
"""
edges is a list of tuples
"""
return [(idx[e[0]], idx[e[1]]) for e in edges] |
def prob(val):
""" validates the range of (connection) probability"""
if not (type(val) == float and 0.0 <= val <= 1.0):
raise ValueError("0.0 <= val <= 1.0 is the correct range")
else:
return val |
def is_divisor(a, b) -> bool:
"""
check if a is a divisor of b
:param a: a positive integer
:param b: b positive integer
:return: True if a is a divisor of b, False otherwise
"""
a, b = int(a), int(b)
return a % b == 0 |
def _precursor_to_interval(mz: float, charge: int, interval_width: int) -> int:
"""
Convert the precursor m/z to the neutral mass and get the interval index.
Parameters
----------
mz : float
The precursor m/z.
charge : int
The precursor charge.
interval_width : int
The width of each m/z interval.
Returns
-------
int
The index of the interval to which a spectrum with the given m/z and
charge belongs.
"""
hydrogen_mass, cluster_width = 1.00794, 1.0005079
neutral_mass = (mz - hydrogen_mass) * max(abs(charge), 1)
return round(neutral_mass / cluster_width) // interval_width |
def _algo_check_for_section_problems(ro_rw_zi):
"""Return a string describing any errors with the layout or None if good"""
s_ro, s_rw, s_zi = ro_rw_zi
if s_ro is None:
return "RO section is missing"
if s_rw is None:
return "RW section is missing"
if s_zi is None:
return "ZI section is missing"
if s_ro["sh_addr"] != 0:
return "RO section does not start at address 0"
if s_ro["sh_addr"] + s_ro["sh_size"] != s_rw["sh_addr"]:
return "RW section does not follow RO section"
if s_rw["sh_addr"] + s_rw["sh_size"] != s_zi["sh_addr"]:
return "ZI section does not follow RW section"
return None |
def size_partitions(pplan, diskmbsize):
"""Do simple math on partitions and figure out the size of partitions."""
part0 = None
for part in pplan:
if part.size == 0:
if part0 is not None:
raise Exception("cannot have two flex size partitions.")
part0 = part
continue
diskmbsize = diskmbsize - part.size
pass
if part0:
diskmbsize = diskmbsize - 1
part0.size = diskmbsize
pass
partion_start = 0
for part in pplan:
part.start = partion_start
partion_start = partion_start + part.size
pass
return pplan |
def lcm_trial(a,b):
"""
Finds the least common multiple of
2 numbers without using GCD
"""
greater = b if a < b else a
while(True):
if ((greater % a == 0) & (greater % b == 0)):
lcm = greater
break
greater += 1
return lcm |
def _max_job_size(job_size):
""" Formatting job size 'X-Y' """
job_size = job_size.split('-')
if len(job_size) > 1:
return int(job_size[1])
else:
return int(job_size[0]) |
def merge_items_categories(items, categories, debug=False):
"""
Function to merge categories into dicts of items to finalize the date in a single variable.
:param items: list of dicts containing item information
:param categories: dict of dicts containing category information
:param debug: Boolean to print stuff on console for debugging
:return: List of dicts containing item information including their categories
"""
for item in items:
if item['category_id']:
item['category'] = categories[item['category_id']]
return items |
def dot_get(data, key='', default=None, copy=False):
"""Retrieve key value from data using dot notation
Arguments:
data {mixed} -- data source
Keyword Arguments:
key {str} -- key using dot notation (default: {''})
default {mixed} -- default value if key does not exist (default: {None})
copy {bool} -- create a copy of the value (to break memory refence) (default: {False})
Returns:
mixed
"""
from copy import deepcopy
nodes = [n for n in [n.strip() for n in key.split('.') if n]]
if nodes:
for i, node in enumerate(nodes):
if isinstance(data, dict):
if i + 1 == len(nodes) and node in data.keys():
return data[node]
else:
if node in data.keys():
data = data[node]
else:
break
else:
return deepcopy(data) if copy else data
return default |
def sd_to_rsd(ccs_avg, ccs_sd):
""" converts CCS SD into RSD % """
return 100. * ccs_sd / ccs_avg |
def is_within_range(nagstring, value):
"""check if the value is withing the nagios range string
nagstring -- nagios range string
value -- value to compare
Returns true if within the range, else false
"""
if not nagstring:
return False
import re
#import operator
first_float = r'(?P<first>(-?[0-9]+(\.[0-9]+)?))'
second_float = r'(?P<second>(-?[0-9]+(\.[0-9]+)?))'
actions = [ (r'^%s$' % first_float,
lambda y: (value > float(y.group('first'))) or (value < 0)),
(r'^%s:$' % first_float,
lambda y: value < float(y.group('first'))),
(r'^~:%s$' % first_float,
lambda y: value > float(y.group('first'))),
(r'^%s:%s$' % (first_float,second_float),
lambda y: (value < float(y.group('first'))) or
(value > float(y.group('second')))),
(r'^@%s:%s$' % (first_float,second_float),
lambda y: not((value < float(y.group('first'))) or
(value > float(y.group('second')))))]
for regstr, func in actions:
res = re.match(regstr, nagstring)
if res:
return func(res)
raise Exception('Improper warning/critical parameter format.') |
def get_word_count(dictionary, text):
"""
counts the number of words from a tweet that is present in the given dictionary.
@param text:
@param dictionary:
@return:
"""
count = 0
for word in dictionary:
#print word, count
#print word, "----", count
if word in text:
#print word
count += 1
return count |
def isfloat(x):
"""Checks if x is convertible to float type.
If also checking if x is convertible to int type, this must be done before since
this implies x is also convertible to float.
"""
try:
a = float(x)
except ValueError:
return False
else:
return True |
def id_force_tuple(id):
"""Convert id into tuple form."""
if isinstance(id, tuple) and all(isinstance(i, int) for i in id):
return id
elif isinstance(id, int):
return (id,)
elif isinstance(id, str):
return tuple(int(s) for s in id.split("."))
else:
raise TypeError() |
def reserved(word):
"""Parse for any reserved words.
This is needed for words such as "class", which is used in html but
reserved in Python.
The convention is to use "word_" instead.
"""
if word == 'class_':
return 'class'
return word |
def cap_value(a, min_, max_):
""" common/utils.h:23 """
"""Check if 'a' fits in (min, max).
If not - returns 'min' or 'max', respectively"""
return max_ if a >= max_ else min_ if a <= min_ else a |
def append_querystring( request, exclude = None ):
"""
Returns the query string for the current request, minus the GET parameters
included in the `exclude`.
"""
exclude = exclude or ['page']
if request and request.GET:
amp = '&'
return amp + amp.join(
[ '%s=%s' % (k,v)
for k,v in request.GET.items()
if k not in exclude ]
)
return '' |
def color_mapping_func(labels, mapping):
"""Mapea etiquetas en formato entero o cadena a un color cada una."""
color_list = [mapping[value] for value in labels]
return color_list |
def wrapHA(ha):
"""Force ha into range -180 to 180. Just to be sure.
"""
if -180 < ha <= 180:
return ha
while ha > 180:
ha = ha - 360.
while ha <= -180:
ha = ha + 360.
assert -180 < ha <= 180, "ha = {:.2f}".format(ha)
return ha |
def get_request_body(request):
"""Get a request's body (POST data). Works with all Django versions."""
return getattr(request, 'body', getattr(request, 'raw_post_data', '')) |
def gamma_approx(mean, variance):
"""
Returns alpha and beta of a gamma distribution for a given mean and variance
"""
return (mean ** 2) / variance, mean / variance |
def str_to_raw(str):
"""Convert string received from commandline to raw (unescaping the string)"""
try: # Python 2
return str.decode('string_escape')
except: # Python 3
return str.encode().decode('unicode_escape') |
def reverseByteOrder(data):
"""Reverses the byte order of an int (16-bit) or long (32-bit) value."""
# Courtesy Vishal Sapre
byteCount = len(hex(data)[2:].replace('L','')[::2])
val = 0
for i in range(byteCount):
val = (val << 8) | (data & 0xff)
data >>= 8
return val |
def score_length(word):
"""Return a score, 1-5, of the length of the word.
Really long, or really short words get a lower score.
There is no hard science, but popular opinion suggests
that a word somewhere between 8-15 letters is optimal.
:param word (str): The word to score.
:rtype score (int): The resulting score.
"""
if not word or len(word) == 0:
return 0
_len = len(word)
# 20+
if _len > 20:
return 1
# 15-20
elif _len > 15 and _len <= 20:
return 2
# 1-4
elif _len <= 4:
return 3
# 10-15
elif _len >= 10 and _len <= 15:
return 4
# 5-10
elif _len > 4 and _len < 10:
return 5 |
def get_image_urls(ids):
"""function to map ids to image URLS"""
return [f"http://127.0.0.1:8000/{id}" for id in ids] |
def concatenate_number(a, b): # O(1)
"""
Concatenates two number together
>>> concatenate_number(4, 2)
42
>>> concatenate_number(-4, 2)
-42
>>> concatenate_number(-43, 2)
-432
>>> concatenate_number(0, 7)
7
"""
if a >= 0: # O(1)
return (a * 10) + b # O(1)
return (a * 10) - b # O(1) |
def format_max_width(text, max_width=None, **kwargs):
"""
Takes a string and formats it to a max width seperated by carriage
returns
args:
max_width: the max with for a line
kwargs:
indent: the number of spaces to add to the start of each line
prepend: text to add to the start of each line
"""
ind = ''
if kwargs.get("indent"):
ind = ''.ljust(kwargs['indent'], ' ')
prepend = ind + kwargs.get("prepend", "")
if not max_width:
return "{}{}".format(prepend, text)
len_pre = len(kwargs.get("prepend", "")) + kwargs.get("indent", 0)
test_words = text.split(" ")
word_limit = max_width - len_pre
if word_limit < 3:
word_limit = 3
max_width = len_pre + word_limit
words = []
for word in test_words:
if len(word) + len_pre > max_width:
n = max_width - len_pre
words += [word[i:i + word_limit]
for i in range(0, len(word), word_limit)]
else:
words.append(word)
idx = 0
lines = []
idx_limit = len(words) - 1
sub_idx_limit = idx_limit
while idx < idx_limit:
current_len = len_pre
line = prepend
for i, word in enumerate(words[idx:]):
if (current_len + len(word)) == max_width and line == prepend:
idx += i or 1
line += word
lines.append(line)
if idx == idx_limit:
idx -= 1
sub_idx_limit -= 1
del words[0]
break
if (current_len + len(word) + 1) > max_width:
idx += i
if idx == idx_limit:
idx -= 1
sub_idx_limit -= 1
del words[0]
if idx == 0:
del words[0]
lines.append(line)
break
if (i + idx) == sub_idx_limit:
idx += i or 1
if line != prepend:
line = " ".join([line, word])
elif word:
line += word
lines.append(line)
else:
if line != prepend:
line = " ".join([line, word])
elif word:
line += word
current_len = len(line)
return "\n".join(lines) |
def contains_dollar_sign(input_string):
"""
check if string contains '$'
>>> contains_dollar_sign("$5")
True
>>> contains_dollar_sign("5")
False
"""
return any(_ == "$" for _ in input_string) |
def yields_from_gronow_2021_tables_3_A10(feh):
"""
Supernova data source: Gronow, S. et al., 2021, A&A, Tables 3/A10 He detonation + Core detonation
Five datasets are provided for FeH values of -2, -1, 0 and 0.4771
We use four intervals delimited by midpoints of those values.
"""
if feh <= -1.5:
return [2.81e-2, 9.85e-6, 4.23e-9, 1.25e-7, 5.72e-3, 1.85e-6, 3.29e-4, 1.10e-1, 7.14e-2, 1.76e-2, 7.85e-1]
elif -1.5 < feh <= -0.5:
return [2.81e-2, 9.72e-6, 4.21e-9, 1.16e-6, 5.72e-3, 2.08e-6, 3.38e-4, 1.10e-1, 7.15e-2, 1.76e-2, 7.85e-1]
elif -0.5 < feh <= 0.239:
return [2.75e-2, 2.74e-5, 3.87e-9, 1.71e-5, 5.82e-3, 7.58e-6, 3.30e-4, 1.10e-1, 7.01e-2, 1.68e-2, 7.62e-1]
elif 0.239 <= feh:
return [2.45e-2, 8.64e-6, 3.65e-9, 3.46e-5, 5.99e-3, 1.01e-5, 2.94e-4, 1.10e-1, 6.46e-2, 1.49e-2, 6.91e-1] |
def _get_bin_width(stdev, count):
"""Return the histogram's optimal bin width based on Sturges
http://www.jstor.org/pss/2965501
"""
w = int(round((3.5 * stdev) / (count ** (1.0 / 3))))
if w:
return w
else:
return 1 |
def calculate_checksum(spreadsheet):
"""Calculates the checksum of a spreadsheet, which is the sum of every row's difference of its
highest and lowest value."""
checksum = 0
for row in spreadsheet:
for number in row:
i = 0
found = False
while i < len(row) and not found:
if row[i] != number and (row[i] % number == 0):
found = True
checksum += row[i] / number
i += 1
return checksum |
def generate_state(td_count: int, node_count: int, records_count: int, ttl: int):
"""Utility method to generate a state dict"""
return {
f"td{i}.example.com": {
"name": f"td{i}.example.com",
"nodes": [f"node{n}" for n in range(node_count)],
"records": [
{"hostname": f"rec{r}", "weight": 100} for r in range(records_count)
],
"ttl": ttl,
}
for i in range(td_count)
} |
def readFile( in_path ):
"""Return content of file at given path"""
with open( in_path, 'r' ) as in_file:
contents = in_file.read()
return contents |
def generate_char_set(classes, repeat_times):
"""returns a full list of characters for the user to input"""
return [c for c in classes for i in range(repeat_times)] |
def extend_conv_spec(convolutions):
"""
Extends convolutional spec that is a list of tuples of 2 or 3 parameters
(kernel size, dim size and optionally how many layers behind to look for residual)
to default the residual propagation param if it is not specified
"""
extended = []
for spec in convolutions:
if len(spec) == 3:
extended.append(spec)
elif len(spec) == 2:
extended.append(spec + (1,))
else:
raise Exception('invalid number of parameters in convolution spec ' + str(spec) + '. expected 2 or 3')
return tuple(extended) |
def to_man_exp(s):
"""Return (man, exp) of a raw mpf. Raise an error if inf/nan."""
sign, man, exp, bc = s
if (not man) and exp:
raise ValueError("mantissa and exponent are undefined for %s" % man)
return man, exp |
def npv(Rn, i, i0, pe=0):
"""Net present value (NPV) is the difference between
the present value of cash inflows and the present value
of cash outflows over a period of time.
Args:
Rn: Expected return list
i: Discount rate
i0: Initial amount invested
pe: Profit or expense at the end of investment
Returns:
Net present value
Example:
Given the expected return list `Rn`, `i` as
discount rate, and `i0` as initial amount invested
you can calcuate NPV like this:
>>> import malee
>>> malee.npv([5000, 8000, 12000, 30000], 0.05, 40000)
7065.266015703324
"""
npv_sum = 0
for idx, Ri in enumerate(Rn):
if Ri == Rn[-1] and pe != 0:
npv_sum += Ri + pe / ((1 + i) ** (idx + 1))
else:
npv_sum += Ri / ((1 + i) ** (idx + 1))
return npv_sum - i0 |
def rgb2hex(r, g, b):
"""
@return: RGB color in HEX format
@rtype: str
"""
return "#{:02x}{:02x}{:02x}".format(r, g, b) |
def _file_lines(fname):
"""Return the contents of a named file as a list of lines.
This function never raises an IOError exception: if the file can't be
read, it simply returns an empty list."""
try:
outfile = open(fname)
except IOError:
return []
else:
out = outfile.readlines()
outfile.close()
return out |
def _similarity_measure(x, y, constant):
"""
Calculate feature similarity measurement between two images
"""
numerator = 2 * x * y + constant
denominator = x ** 2 + y ** 2 + constant
return numerator / denominator |
def features_to_tokens(features):
"""
Method to convert list of atomic features into a list of tokens.
:param features: List of atomic features.
:return: A list of tokens.
"""
result = []
for feature in features:
result.extend(feature.tokens)
return result |
def get_all_parms(kwargs, unlocked_only=False):
"""Get all (both normal and locked) parms, related to an RMB menu click.
"""
r = None
try:
r = kwargs["parms"]
if not unlocked_only:
r += kwargs["locked_parms"]
except:
pass
return r |
def response(attributes, speech_response):
""" create a simple json response """
return {
'version': '1.0',
'sessionAttributes': attributes,
'response': speech_response
} |
def is_an_oak(name):
""" Returns True if name is starts with 'quercus '
>>> is_an_oak('quercus')
True
"""
return name.lower().startswith('quercus ') |
def sanitize_ident(x, is_clr=False):
"""Takes an identifier and returns it sanitized"""
if x in ("class", "object", "def", "list", "tuple", "int", "float", "str", "unicode" "None"):
return "p_" + x
else:
if is_clr:
# it tends to have names like "int x", turn it to just x
xs = x.split(" ")
if len(xs) == 2:
return sanitize_ident(xs[1])
return x.replace("-", "_").replace(" ", "_").replace(".", "_") |
def format_entity(str_to_replace):
"""Replace space between toks by the character "_"
Ex: "id hang_hoa" = "id_hang_hoa"
"""
return str_to_replace.replace(" ", "_") |
def iloss(price_ratio, numerical=False):
"""return the impermanent loss result in compare with buy&hold A&B assets
Args:
price_ratio (float): Variation A Asset / Variation B Asset
price_ratio formula:
price_ratio = (var_A/100 + 1) / (var_B/100 + 1)
var_A: Asset A % variation
var_B: Asset B % variation
numerical (bool): if True, returns impermanent loss as a decimal expr, ie "5%"" => 0.05 (Default: False)
Returns:
TYPE: impermanent loss as a string percentual value
"""
il = 2 * (price_ratio**0.5 / (1 + price_ratio)) - 1
r = f"{il:.2%}" if not numerical else il
return r |
def matrix_block(symbs, key_mat, name_mat, delim=' '):
""" Write the Z-matrix block, where atoms and coordinates are defined,
to a string.
:param symbs: atomic symbols of the atoms
:type symbs: tuple(str)
:param key_mat: key/index columns of the z-matrix, zero-indexed
:type key_mat: tuple[tuple[float, float or None, float or None]]
:param name_mat: coordinate name columns of the z-matrix
:type name_mat; tuple[tuple[str, str or None, str or None]]
:param delim: delimiter for the columns of the Z-matrix block
:type delim: str
:rtype: str
"""
def _line_string(row_idx):
line_str = '{:<2s} '.format(symbs[row_idx])
keys = key_mat[row_idx]
names = name_mat[row_idx]
line_str += delim.join([
'{:>d}{}{:>5s} '.format(keys[col_idx], delim, names[col_idx])
for col_idx in range(min(row_idx, 3))])
return line_str
natms = len(symbs)
mat_str = '\n'.join([_line_string(row_idx) for row_idx in range(natms)])
return mat_str |
def ALL_ELEMENTS_TRUE(*expressions):
"""
Evaluates an array as a set and returns true if no element in the array is false. Otherwise, returns false.
An empty array returns true.
https://docs.mongodb.com/manual/reference/operator/aggregation/allElementsTrue/
for more details
:param expressions: The arrays (expressions)
:return: Aggregation operator
"""
return {'$allElementsTrue': list(expressions)} |
def change_dictkeys(obj, function):
"""Apply function to each dict-key"""
if isinstance(obj, list):
return [change_dictkeys(v, function) for v in obj]
if isinstance(obj, dict):
return {function(k): change_dictkeys(v, function) for k, v in obj.items()}
return obj |
def find_patient_all(patient_id, patients_db):
"""Find all data for one patient from database
This function pulls the patients' all dictionary based on the
patient_id entered in the json file. If the entered patient_id is
not found in the patient database, then a False boolean is returned.
This output is used in the heart_rate_timestamp function.
:param patient_id: The patient_id number from the inputted json as an
integer
:param patients_db: The master database containing dictionaries for each
entered patient
:returns: This function will return a list of all data from one specific
patient id corresponding to the entered patient_id number.
"""
find_all_list = []
for patient in patients_db:
if patient["patient_id"] == patient_id:
for key in {"timestamp": [], "heart_rate": []}:
if key in patient:
find_all_list.append(patient)
break
return find_all_list |
def d_phi_dyy(x, y):
"""
second derivative of the orientation angle in dydy
:param x:
:param y:
:return:
"""
return -2 * x * y / (x ** 2 + y ** 2) ** 2 |
def _conv_type(s, func):
"""Generic converter, to change strings to other types.
Args:
s (str): String that represents another type.
func (function): Function to convert s, should take a singe parameter
eg: int(), float()
Returns:
The type of func, otherwise str
"""
if func is not None:
try:
return func(s)
except ValueError:
return s
return s |
def converter_parameter_to_int(value):
"""
Converts the given value to string.
Parameters
----------
value : `str`
The value to convert to string.
Returns
-------
value : `None` or `int`
Returns `None` if conversion failed.
"""
try:
value = int(value)
except ValueError:
value = None
return value |
def _eval_checksum(data, constrain=True):
"""
Evaluate the expected checksum for specific data row.
This function accepts a string, and calculates the checksum
of the bytes provided.
Parameters
----------
data: [str, bytes]
The bytestring which should be evaluated for the
checksum.
constrain: bool, optional
Control to specify whether the value should be
constrained to an 8-bit representation, defaults
to False.
Returns
-------
checksum: int
The fully evaluated checksum.
"""
# Evaluate the sum
if isinstance(data, str):
checksum = sum(map(ord, data))
else:
checksum = sum(data)
# Cap the Value if Needed
if constrain:
checksum = checksum & 0xffff # Bit-wise AND with 16-bit maximum
return checksum |
def increment_name(name: str, start_marker: str = " (",
end_marker: str = ")") -> str:
"""
Increment the name where the incremental part is given by parameters.
Parameters
----------
name : str, nbformat.notebooknode.NotebookNode
Name
start_marker : str
The marker used before the incremental
end_marker : str
The marker after the incrementa
Returns
-------
str
Incremented name.
>>> increment_name('abc')
'abc (1)'
>>> increment_name('abc(1)')
'abc(1) (1)'
>>> increment_name('abc (123)')
'abc (124)'
>>> increment_name('abc-1',start_marker='-',end_marker='')
'abc-2'
>>> increment_name('abc[2]',start_marker='[',end_marker=']')
'abc[3]'
>>> increment_name('abc1',start_marker='',end_marker='')
Traceback (most recent call last):
...
ValueError: start_marker can not be the empty string.
"""
if start_marker == '':
raise ValueError("start_marker can not be the empty string.")
a = name
start = len(a)-a[::-1].find(start_marker[::-1])
if (a[len(a)-len(end_marker):len(a)] == end_marker
and start < (len(a)-len(end_marker))
and a[start-len(start_marker):start] == start_marker
and a[start:len(a)-len(end_marker)].isdigit()):
old_int = int(a[start:len(a)-len(end_marker)])
new_int = old_int+1
new_name = a[:start]+str(new_int)+end_marker
else:
new_name = a+start_marker+'1'+end_marker
return new_name |
def read_row(row):
"""Reads a row of a crossword puzzle and decomposes it into a list. Every
'#' is blocking the current box. Letters 'A', ..., 'Z' and 'a', ..., 'z'
are values that are already filled into the box. These letters are capitalized
and then put into the list. All other characters stand
for empty boxes which are represented by a space ' ' in the list.
Examples:
read_row('#.#') gives ['#', ' ', '#']
read_row('C.T') gives ['C', ' ', 'T']
read_row('cat') gives ['C', 'A', 'T']
"""
lower = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
upper = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
list = []
for char in row:
if char in lower:
list.append(char.upper())
elif char in upper:
list.append(char)
elif char == '#':
list.append('#')
else:
list.append(' ')
return list |
def get_activity_id(activity_name):
"""Get activity enum from it's name."""
activity_id = None
if activity_name == 'STAND':
activity_id = 0
elif activity_name == 'SIT':
activity_id = 1
elif activity_name == 'WALK':
activity_id = 2
elif activity_name == 'RUN':
activity_id = 3
elif activity_name == 'WALK_UPSTAIRS':
activity_id = 4
elif activity_name == 'WALK_DOWNSTAIRS':
activity_id = 5
elif activity_name == 'LIE':
activity_id = 6
elif activity_name == 'BIKE':
activity_id = 7
elif activity_name == 'DRIVE':
activity_id = 8
elif activity_name == 'RIDE':
activity_id = 9
else:
activity_id = 10
return activity_id |
def prepend_a_an(name):
"""Add a/an to a name"""
if name[0] in ["a", "e", "i", "o", "u"]:
return "an " + name
else:
return "a " + name |
def min_divisible_value(n1, v1):
""" make sure v1 is divisible by n1, otherwise decrease v1 """
if v1 >= n1:
return n1
while n1 % v1 != 0:
v1 -= 1
return v1 |
def sources(capacity_factor: bool = True):
"""
This function provides the links to the sources used
for obtaining certain information. The arguments
can either be set to the appropriate boolean based
on the sources required.
Parameters:
-----------
capacity_factor: bool
This argument determines whether the sources for the
capacity factor data will be returned. Default is True.
"""
if not isinstance(capacity_factor, bool):
raise TypeError(
"Argument 'capacity_factor' must be of type 'bool'."
)
if capacity_factor is True:
print(
'Capacity Factor Sources:'
)
print(
'https://www.statista.com/statistics/183680/us-aver' +
'age-capacity-factors-by-selected-energy-source-since-1998/'
)
print(
'https://www.eia.gov/electricity/monthly/epm_table_grapher.ph' +
'p?t=epmt_6_07_a'
)
print(
'https://www.hydrogen.energy.gov/pdfs/review16/tv016_saur_2016' +
'_p.pdf'
)
return None |
def is_natural(num: int):
"""Test if the number is natural."""
if not (isinstance(num, int) and num > 0):
return False
return True |
def get_node_text(node_list, do_strip=False):
"""Returns the complete text from the given node list (optionally stripped) or None if the list is empty."""
if(len(node_list) == 0):
return None
text = u""
for node in node_list:
if node.nodeType == node.TEXT_NODE:
text += node.data
if do_strip:
text = text.strip()
return text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.