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, o... |
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 ... |
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
... |
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.
... |
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... |
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 co... |
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([... |
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).
... |
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
... |
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:
... |
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( ... |
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 = {
'... |
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 th... |
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. ... |
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 i... |
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("&", "&")
... |
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... |
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
... |
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
T... |
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 ... |
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 = d... |
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 ... |
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 (defa... |
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 ... |
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:... |
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' %... |
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... |
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: ... |
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 st... |
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:... |
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 ... |
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": [
... |
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 c... |
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 expens... |
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.re... |
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
... |
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)
... |
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 ... |
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: T... |
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 out... |
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
""... |
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(v... |
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... |
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 ma... |
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
... |
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':
acti... |
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 argu... |
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.d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.