content
stringlengths 42
6.51k
|
---|
def expression_parser(expression, numeric):
"""Parse an uncomplete math expression e.g. '* 10' and apply it to supplied attribute.
Parameters
----------
expression : string
Incomplete math expression in the form '* 5' or '- 10'. Can also be empty to leave
numeric un-affected.
numeric : int or float
Value to evaluate against expression.
Returns
-------
The full expression evaluated.
"""
# is expression a string?
if not isinstance(expression, str):
raise TypeError("expression should be a string.")
elif not isinstance(numeric, (int, float)):
raise TypeError("numeric should be an integer or a float.")
# If expression is empty, we return the numeric.
elif expression == "":
return numeric
else:
# Extract the operator
operator = expression[0]
if operator not in ["*", "/", "+", "-"]:
raise ValueError(
"First part of expression should be either one of *, /, +, -."
)
# Extract the factor
factor = float(expression[1:])
# Create a table of possible expressions. Then we just pick the correct one for return.
expression_dict = {
"*": numeric * factor,
"/": numeric / factor,
"+": numeric + factor,
"-": numeric - factor,
}
return expression_dict[operator]
|
def next_power_of_2(x: int):
"""
Returns the smallest power of two which is >= x.
"""
assert isinstance(x, int) and x > 0
res = 2 ** (x - 1).bit_length()
assert x <= res < 2 * x, f'{x}, {res}'
return res
|
def get_hit_table(hit):
"""Create context for a single hit in the search.
Args:
hit(Dict): a dictionary representing a single hit in the search.
Returns:
(dict).The hit context.
(list).the headers of the hit.
"""
table_context = {
'_index': hit.get('_index'),
'_id': hit.get('_id'),
'_type': hit.get('_type'),
'_score': hit.get('_score'),
}
headers = ['_index', '_id', '_type', '_score']
if hit.get('_source') is not None:
for source_field in hit.get('_source').keys():
table_context[str(source_field)] = hit.get('_source').get(str(source_field))
headers.append(source_field)
return table_context, headers
|
def get_destroyed_volume(vol, array):
"""Return Destroyed Volume or None"""
try:
return bool(array.get_volume(vol, pending=True)["time_remaining"] != "")
except Exception:
return False
|
def check_object_inconsistent_identifier(frm_list, tubes):
"""
checking whether boxes are lost during the track
"""
valid_flag = False
for tube_id, tube_info in enumerate(tubes):
if tube_info[frm_list[0]]!=[0,0,1,1]:
for tmp_id in range(1, len(frm_list)):
tmp_frm = frm_list[tmp_id]
if tube_info[tmp_frm]==[0, 0, 1, 1]:
valid_flag=True
return valid_flag
return valid_flag
|
def is_not_csv_file(filename):
"""Retun an indication if the file entered is the clusterserviceversion (csv) file """
return not filename.endswith('clusterserviceversion.yaml')
|
def estimate_s3_conversion_cost(
total_mb: float,
transfer_rate_mb: float = 20.0,
conversion_rate_mb: float = 17.0,
upload_rate_mb: float = 40,
compression_ratio: float = 1.7,
):
"""
Estimate potential cost of performing an entire conversion on S3 using full automation.
Parameters
----------
total_mb: float
The total amount of data (in MB) that will be transferred, converted, and uploaded to dandi.
transfer_rate_mb: float, optional
Estimate of the transfer rate for the data.
conversion_rate_mb: float, optional
Estimate of the conversion rate for the data. Can vary widely depending on conversion options and type of data.
Figure of 17MB/s is based on extensive compression of high-volume, high-resolution ecephys.
upload_rate_mb: float, optional
Estimate of the upload rate of a single file to the DANDI archive.
compression_ratio: float, optional
Esimate of the final average compression ratio for datasets in the file. Can vary widely.
"""
c = 1 / compression_ratio # compressed_size = total_size * c
total_mb_s = (
total_mb**2 / 2 * (1 / transfer_rate_mb + (2 * c + 1) / conversion_rate_mb + 2 * c**2 / upload_rate_mb)
)
cost_gb_m = 0.08 / 1e3 # $0.08 / GB Month
cost_mb_s = cost_gb_m / (1e3 * 2.628e6) # assuming 30 day month; unsure how amazon weights shorter months?
return cost_mb_s * total_mb_s
|
def merge(lst1, lst2):
"""Merges two sorted lists.
>>> merge([1, 3, 5], [2, 4, 6])
[1, 2, 3, 4, 5, 6]
>>> merge([], [2, 4, 6])
[2, 4, 6]
>>> merge([1, 2, 3], [])
[1, 2, 3]
>>> merge([5, 7], [2, 4, 6])
[2, 4, 5, 6, 7]
"""
"*** YOUR CODE HERE ***"
if lst1 == []:
return lst2
elif lst2 ==[]:
return lst1
elif lst1[0] <= lst2[0]:
return lst1[:1] + merge(lst1[1:], lst2)
else:
return lst2[:1] + merge(lst1, lst2[1:])
|
def cauchy(x0, gx, x):
"""1-D Cauchy. See http://en.wikipedia.org/wiki/Cauchy_distribution"""
#return INVPI * gx/((x-x0)**2+gx**2)
gx2 = gx * gx
return gx2 / ((x-x0)**2 + gx2)
|
def max_of(a, b):
"""
Returns the larger of the values a and b.
"""
if a >= b:
return a
return b
|
def add(a, b):
""" Addiert die beiden Matrizen a, b komponentenweise.
Gibt das Resultat der Addition als neue Matrix c aus. """
n = len(a)
c = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
c[i][j] = a[i][j] + b[i][j]
return c
|
def isDelimited(value):
"""
This method simply checks to see if the user supplied value has delimiters.
That is, if it starts and ends with double-quotes, then it is delimited.
"""
if len(value) < 2:
return False
if value[0] == '"' and value[-1] == '"':
return True
else:
return False
|
def generate_fasta_dict(sec_record_list):
"""
Creates a dictionary containing FASTA formatted strings from a list of sequence record objects.
This dictionary is keyed by the sequence ID.
:param sec_record_list: List of Biopython sequence record objects.
:return: Dictionary containing FASTA formatted strings.
"""
fasta_string_dict = {}
for record in sec_record_list:
fasta_string_dict[record.id] = record.format("fasta")
return fasta_string_dict
|
def rgb2int(r, g, b):
""" rgba2int: Converts an RGB value into an integer
:param r The red value (0-255)
:param g The green value (0-255)
:param b The blue value (0-255)
:returns: The RGB value compact into a 24 byte integer.
"""
r, g, b = int(abs(r)), int(abs(g)), int(abs(b))
return (r << 16) + (g << 8) + b
|
def init_nested_dict_zero(first_level_keys, second_level_keys):
"""Initialise a nested dictionary with two levels
Parameters
----------
first_level_keys : list
First level data
second_level_keys : list
Data to add in nested dict
Returns
-------
nested_dict : dict
Nested 2 level dictionary
"""
nested_dict = {}
for first_level_key in first_level_keys:
nested_dict[first_level_key] = {}
for second_level_key in second_level_keys:
nested_dict[first_level_key][second_level_key] = 0
return nested_dict
|
def update_key_value(contents, key, old_value, new_value):
"""
Find key in the contents of a file and replace its value with the new value,
returning the resulting file. This validates that the old value is constant and
hasn't changed since parsing its value.
Raises a ValueError when the key cannot be found in the given contents.
Does not modify the value of contents.
"""
new_contents = contents[:]
old_line = key + ": " + old_value
updated = False
for line_num in range(0, len(new_contents)):
line = new_contents[line_num]
if line == old_line:
new_contents[line_num] = key + ": " + new_value
updated = True
break
if not updated:
raise ValueError("For key:%s, cannot find the old value (%s) in the given "
"contents." % (key, old_value))
return new_contents
|
def binarize_preds(predictions, threshold=0.5, debug=False):
"""
Converts real-value predictions between 0 and 1 to integer class values 0
and 1 according to a threshold.
Parameters:
-----------------
predictions: predicted values
threshold: threshold for converting prediction to 0 or 1
debug: Boolean indicating whether or not to print additional information;
default=False
Returns:
-----------------
pred_binary: binarized predictions
"""
pred_binary = []
for prediction in predictions:
if prediction < threshold:
pred_binary.append(0)
else: pred_binary.append(1)
if debug:
print(predictions)
print(pred_binary)
return pred_binary
|
def check_coarse_parallel(msgs):
# type: (str) -> bool
"""
Check if coarse parallel is enabled as expected
"""
for msg in msgs:
if msg.find('\"coarse_grained_parallel": \"off') != -1:
return False
return True
|
def _build_pruned_tree(tree, cases, tree2):
"""helper method for ``build_pruned_tree``"""
is_results = False
if isinstance(tree[0], str):
try:
name, icase, cases2 = tree
except ValueError:
print(tree)
raise
if isinstance(icase, int):
assert cases2 == [], tree
if icase in cases:
is_results = True
tree2.append(tree)
else:
assert icase is None, tree
tree3 = []
for case in cases2:
is_resultsi, tree3 = _build_pruned_tree(case, cases, tree3)
if is_resultsi:
is_results = True
if is_results:
tree2.append((name, icase, tree3))
else:
tree3 = []
for case in tree:
is_resultsi, tree3 = _build_pruned_tree(case, cases, tree3)
if is_resultsi:
is_results = True
tree2 = tree3
return is_results, tree2
|
def get_scope_preview(value, n):
"""
Get the top N lines of a ``scope`` list for an individual :model:`rolodex.ProjectScope`.
**Parameters**
``value``
The ``scope`` value of an individual :model:`rolodex.ProjectScope` entry
``value``
Number of lines to return
"""
return "\n".join(value.split("\r\n")[0:n])
|
def card_average(hand):
"""
:param hand: list - cards in hand.
:return: float - average value of the cards in the hand.
"""
total = 0
for card in hand:
total += card
return total / len(hand)
|
def between_markers(text: str, begin: str, end: str) -> str:
"""
returns substring between two given markers
"""
return ('' if len(text.split(begin)[0]) > len(text.split(end)[0]) and
begin in text and end in text else
text.split(begin)[-1].split(end)[0] if begin in text and
end in text else
text.split(begin)[-1] if begin in text else
text.split(end)[0] if end in text else text)
|
def pair_sum_eff(A, n=0):
"""
O(nlogn) but a memory efficient
"""
A = sorted(A)
lst = []
first = 0
last = len(A) - 1
while first < last:
if A[first] + A[last] == n:
lst.append((A[first], A[last]))
first += 1
last -= 1
elif A[first] + A[last] < n:
first += 1
else:
last -= 1
return lst
|
def func_param_immutable_default_safer(collection=None):
"""
:param collection: a collection. default None which is immutable and therefor safer.
:return: collection by appending 'thing'
"""
if collection is None:
# safer pattern, instantiate a new mutable object inside the function, not as a parameter default.
collection = []
collection.append("thing")
return collection
|
def get_req_key(req_items=[{}]):
"""
Determines the base key in the dict for required items
"""
return [key for key in req_items[0].keys()
if key not in ["description",
"dict_params",
"default_values"]][0]
|
def get_rule_names(rules):
"""Returns a sorted list of rule names from the rules list."""
return sorted([r['name'] for r in rules])
|
def build_describe_query(subject):
"""Create a query SELECT * WHERE { <subject> ?p ?o .}"""
return {
'type': 'bgp',
'bgp': [
{
'subject': subject,
'predicate': '?p',
'object': '?o'
}
]
}
|
def readable_timedelta(days):
"""To get the number of weeks and days in given nuber of days"""
number_of_weeks = days // 7 #To get number of weeks
number_of_days = days % 7 # To get number of days
return('{} week(s) and {} day(s)'.format(number_of_weeks, number_of_days))
|
def nested_set(base, key_list, value):
"""Set a value in a nested object in base by item sequence."""
for key in key_list[:-1]:
base = base.setdefault(key, {})
base[key_list[-1]] = value
return base
|
def hex_to_chars(num):
""" Convert the hex representation of the number to a correctly ordered
string.
Parameters
----------
val: int
The integer representing the string. This is in reverse order.
Ie. XXYYZZ -> chr(ZZ)chr(YY)chr(XX)
Returns
-------
str
The actual string.
"""
# convert to an actual number
return (chr(num & 0xFF)
+ chr((num & 0xFF00) >> 8)
+ chr((num & 0xFF0000) >> 16))
|
def get_one_song_cold_start_recs(title, title_pop_recs, pop_recs, trackID):
"""
Based on title popularity recommender for the cold start scenario!
This method is called for playlists with title info and first song!!
:param title:
:param title_pop_recs:
:param pop_recs:
:return:
"""
t_recs = title_pop_recs[title]
print(len(t_recs), title)
temp2 = [r for r in t_recs if not trackID == r]
if len(temp2) < 500:
for pop_rec in pop_recs:
if pop_rec not in temp2 and trackID != pop_rec:
temp2.append(pop_rec)
if len(temp2) == 500:
break
else:
return temp2[:500]
return temp2
|
def concat_body_paragraphs(body_candidates):
"""
Concatenate paragraphs constituting the question body.
:param body_candidates:
:return:
"""
return ' '.join(' '.join(body_candidates).split())
|
def all_ped_combos_lsts(num_locs=4, val_set=("0", "1")):
"""Return a list of all pedestrian observation combinations (in list format) for a vehicle under the 4 location scheme"""
res = []
if num_locs == 0:
return []
if num_locs == 1:
return [[flag] for flag in val_set]
for comb in all_ped_combos_lsts(num_locs - 1, val_set):
# append a flag for all possible flags
for flag in val_set:
appended = comb + [flag]
res.append(appended)
return res
|
def _parsems(value):
"""Parse a I[.F] seconds value into (seconds, microseconds)."""
if "." not in value:
return int(value), 0
else:
i, f = value.split(".")
return int(i), int(f.ljust(6, "0")[:6])
|
def parse_description(description):
"""
Parses the description of a request/response field.
"""
if description is None:
return None
return description.lstrip(' /*').lstrip(' /**').replace('\n', ' ')
|
def _decode_options(options):
"""Parse options given in str.
When options = 'cutoff = 4.0', options is converted to {'cutoff': 4.0}.
In this implementation (can be modified), using phonopy command line
options, ``options`` is passed by --fc-calc-opt such as::
phonopy --hiphiveph --fc-calc-opt "cutoff = 4" ...
"""
option_dict = {}
for pair in options.split(","):
key, value = [x.strip() for x in pair.split("=")]
if key == "cutoff":
option_dict[key] = float(value)
return option_dict
|
def scenario_ids(scenarios):
"""Parse the scenarios and feed the IDs to the test function."""
return [test_input[1] for test_input in scenarios]
|
def exif2gps(exif_data):
"""
Transform coordinate from DMS into D.D
:param exif_data: image exif data:
:return: degrees in D.D format
"""
if not exif_data:
return None
if isinstance(exif_data[0], tuple):
degree = float(exif_data[0][0] / exif_data[0][1])
else:
degree = float(exif_data[0])
if isinstance(exif_data[1], tuple):
minute = float(exif_data[1][0] / exif_data[1][1])
else:
minute = float(exif_data[1])
if isinstance(exif_data[2], tuple):
second = float(exif_data[2][0] / exif_data[2][1])
else:
second = float(exif_data[2])
return degree + minute / 60.0 + second / 3600.0
|
def quantile(x, percentile):
"""
Returns value of specified quantile of X.
:param list or tuple x: array to calculate Q value.
:param float percentile: percentile (unit fraction).
:return: Q value.
:rtype: int or float
:raise ValueError: when len of x == 0
"""
if x:
p_idx = int(percentile * len(x))
return sorted(x)[p_idx]
else:
raise ValueError('len of x == 0')
|
def unify(lines):
"""
put one statement on each line
"""
results = []
result = []
for line in lines:
result.append(line)
if ";" in line:
results.append("".join(result))
result = []
return results
|
def any_key(m) -> str:
"""Any single key"""
return str(m[0])
|
def subplot_dims(n_plots):
"""Get the number of rows and columns for the give number of plots.
Returns how many rows and columns should be used to have the correct
number of figures available. This doesn't return anything larger than
3 columns, but the number of rows can be large.
Parameters
----------
n_plots: int
The number of subplots which will be plotted
Returns
-------
dims: Tuple[int, int]
The dimensions of the subplots returned as (nrows, ncols)
"""
if n_plots > 9:
n_cols = 3
n_rows = (1 + n_plots) // n_cols
elif n_plots < 2:
n_rows = n_cols = 1
else:
n_cols = 2
n_rows = (1 + n_plots) // n_cols
return n_rows, n_cols
|
def bitlist(n):
"""
Returns a list of bits for a char.
"""
return [n >> i & 1 for i in range(7,-1,-1)]
|
def dec_to_tri(n):
"""
:param n: decimal number to be converted to trinary
:returns: trinary string of the number n
"""
tri_string = ""
while n != 0:
tri_string = str(n % 3) + tri_string
n = n // 3
return tri_string
|
def f_linear(x, a, b):
"""
compute the linear function value with given parameters
Parameters
----------
x: int or vector
independent variable values
a: double
slope parameter
b: double
y-intercept parameter
Returns
-------
evaluated linear fucntion with the given parameters for the given x
"""
return(a * x + b)
|
def transistor_power(vcc_max, i_out, r_load, r_set):
"""Calculate power loss in the transistor."""
r_tot = r_load + r_set
# Find point where power is maximum
max_pwr_i = vcc_max/(2 * r_tot)
load_rdrop = max_pwr_i * r_tot
v_trans = vcc_max - load_rdrop
return max_pwr_i * v_trans
|
def regular_polygon_area(perimeter, apothem):
"""Returns the area of a regular polygon"""
# You have to code here
# REMEMBER: Tests first!!!
return (perimeter * apothem) / 2
|
def get_size_in_nice_string(sizeInBytes):
"""
Convert the given byteCount into a string like: 9.9bytes/KB/MB/GB
"""
for (cutoff, label) in [(1024 * 1024 * 1024, "GB"),
(1024 * 1024, "MB"),
(1024, "KB"),
]:
if sizeInBytes >= cutoff:
return "%.1f %s" % (sizeInBytes * 1.0 / cutoff, label)
if sizeInBytes == 1:
return "1 byte"
else:
bytes = "%.1f" % (sizeInBytes or 0,)
return (bytes[:-2] if bytes.endswith('.0') else bytes) + ' bytes'
|
def _verify_notif_contents(packet):
"""
Verify the contents of a result packet
- Returns False, list of errors if verification fails
OR
- Returns True, None if passes verification
"""
errors = []
# Key "id" not allowed in a JSON-RPC notification
if "id" in packet:
errors.append("Key 'id' is not allowed in a JSON-RPC notification")
# Method isn't in the packet, required key
if "method" not in packet:
errors.append("method")
# We don't want to run this code if either of these keys are missing
# Only run it if failed == False
if not len(errors) > 0:
if not isinstance(packet["method"], str):
errors.append("Key 'method' is not required type str")
# If it exists, "params" must be list or dict
if packet.get("params", None) is not None and \
not isinstance(packet, (dict, list)):
errors.append("Key 'params' is not required structured type "
"(list/dict)")
if len(errors) > 0:
# It failed, so return list of "Missing required key 'KEY'"
# for each 1 length strings (keys) OR
# just the error string if length > 1
return False, ["Missing required key '{}'".format(err)
if len(err.split()) == 1 else err
for err in errors]
else:
# Success, execution to this point means the packet has passed
return True, None
|
def three_list_to_record(three_list):
"""Helper function for csv_to_records to convert list with three
[lname,fname,age_str] to {'last_name': lname, 'first_name': fname, 'age': age_int}
Code checks argument for three entries and third entry being convertible to int.
Args:
three_list(list(str,str,int)): [lname,fname,age]
Returns:
{'last_name': lname, 'first_name': fname, 'age': age_int}
Raises:
ValueError: three_list has not three entries or entry 3 is not int.
"""
if len(three_list) != 3:
raise ValueError('three_list argument did not have three entries')
lname, fname, age_str = three_list
if age_str.isdigit():
age_int = int(age_str)
else:
raise ValueError('three_list[2] (age_str) should convertible to int')
return {'last_name': lname, 'first_name': fname, 'age': age_int}
|
def map_collection(collection, map_fn):
"""Apply ``map_fn`` on each element in ``collection``.
* If ``collection`` is a tuple or list of elements, ``map_fn`` is applied on each element,
and a tuple or list, respectively, containing mapped values is returned.
* If ``collection`` is a dictionary, ``map_fn`` is applied on each value, and a dictionary
containing the mapped values is returned.
* If ``collection`` is ``None``, ``None`` is returned.
* If ``collection`` is a single element, the result of applying ``map_fn`` on it is returned.
Args:
collection: The element, or a tuple of elements.
map_fn: A function to invoke on each element.
Returns:
Collection: The result of applying ``map_fn`` on each element of ``collection``.
The type of ``collection`` is preserved.
"""
if collection is None:
return None
if isinstance(collection, (tuple, list)):
return type(collection)(map_fn(x) for x in collection)
if isinstance(collection, dict):
return {k: map_fn(v) for k, v in collection.items()}
return map_fn(collection)
|
def get_flattened_sub_schema(schema_fields, parent_name=''):
"""Helper function to get flattened sub schema from schema"""
flattened_fields = []
for field in schema_fields:
flattened_field = dict()
if 'list' in field and field['list']:
flattened_fields.extend(get_flattened_sub_schema(field['list'], field['field']+'__'))
else:
flattened_field['name'] = parent_name + field['field']
flattened_field['schemaid'] = field['schemaid']
if 'mapped' in field:
flattened_field['mapped'] = field['mapped']
flattened_fields.append(flattened_field)
return flattened_fields
|
def num_round(num, decimal=2):
"""Rounds a number to a specified number of decimal places.
Args:
num (float): The number to round.
decimal (int, optional): The number of decimal places to round. Defaults to 2.
Returns:
float: The number with the specified decimal places rounded.
"""
return round(num, decimal)
|
def get_option_specs(name, required=False, default=None, help_str='', **kwargs):
""" A wrapper function to get a specification as a dictionary. """
if isinstance(default, int):
ret = {'name':name, 'required':required, 'default':default, 'help':help_str,
'type':int}
elif isinstance(default, float):
ret = {'name':name, 'required':required, 'default':default, 'help':help_str,
'type':float}
else:
ret = {'name':name, 'required':required, 'default':default, 'help':help_str}
for key, value in list(kwargs.items()):
ret[key] = value
return ret
|
def ordered_sequential_search(array, element):
"""
Array must be ordered!
"""
pos = 0
found = False
stopped = False
while pos < len(array) and not found and not stopped:
if array[pos] == element:
found = True
else:
if array[pos] > element:
stopped = True
else:
pos += 1
return found
|
def homo(a):
"""Homogenize, or project back to the w=1 plane by scaling all values by w"""
return [ a[0]/a[3],
a[1]/a[3],
a[2]/a[3],
1 ]
|
def infer_shape(x):
"""Take a nested sequence and find its shape as if it were an array.
Examples
--------
>>> x = [[10, 20, 30], [40, 50, 60]]
>>> infer_shape(x)
(2, 3)
"""
shape = ()
if isinstance(x, str):
return shape
try:
shape += (len(x),)
return shape + infer_shape(x[0])
except TypeError:
return shape
|
def maybe_float(v):
"""Casts a value to float if possible.
Args:
v: The value to cast.
Returns:
A float, or the original value if a cast was not possible.
"""
try:
return float(v)
except ValueError:
return v
|
def str_to_bool(s):
"""
Convert a string to a boolean.
:param s: string to convert
:return: boolean value of string
"""
if s.lower() in ('1', 'true', 't'):
return True
elif s.lower() in ('0', 'false', 'f'):
return False
else:
raise ValueError('Input string \"%s\" was not recognized as a boolean')
|
def normalize(num, lower=0.0, upper=360.0, b=False):
"""Normalize number to range [lower, upper) or [lower, upper].
Parameters
----------
num : float
The number to be normalized.
lower : float
Lower limit of range. Default is 0.0.
upper : float
Upper limit of range. Default is 360.0.
b : bool
Type of normalization. See notes.
Returns
-------
n : float
A number in the range [lower, upper) or [lower, upper].
Raises
------
ValueError
If lower >= upper.
Notes
-----
If the keyword `b == False`, the default, then the normalization
is done in the following way. Consider the numbers to be arranged
in a circle, with the lower and upper marks sitting on top of each
other. Moving past one limit, takes the number into the beginning
of the other end. For example, if range is [0 - 360), then 361
becomes 1. Negative numbers move from higher to lower
numbers. So, -1 normalized to [0 - 360) becomes 359.
If the keyword `b == True` then the given number is considered to
"bounce" between the two limits. So, -91 normalized to [-90, 90],
becomes -89, instead of 89. In this case the range is [lower,
upper]. This code is based on the function `fmt_delta` of `TPM`.
Range must be symmetric about 0 or lower == 0.
Examples
--------
>>> normalize(-270,-180,180)
90
>>> import math
>>> math.degrees(normalize(-2*math.pi,-math.pi,math.pi))
0.0
>>> normalize(181,-180,180)
-179
>>> normalize(-180,0,360)
180
>>> normalize(36,0,24)
12
>>> normalize(368.5,-180,180)
8.5
>>> normalize(-100, -90, 90, b=True)
-80.0
>>> normalize(100, -90, 90, b=True)
80.0
>>> normalize(181, -90, 90, b=True)
-1.0
>>> normalize(270, -90, 90, b=True)
-90.0
"""
from math import floor, ceil
# abs(num + upper) and abs(num - lower) are needed, instead of
# abs(num), since the lower and upper limits need not be 0. We need
# to add half size of the range, so that the final result is lower +
# <value> or upper - <value>, respectively.
res = num
if not b:
if lower >= upper:
raise ValueError("Invalid lower and upper limits: (%s, %s)" %
(lower, upper))
res = num
if num > upper or num == lower:
num = lower + abs(num + upper) % (abs(lower) + abs(upper))
if num < lower or num == upper:
num = upper - abs(num - lower) % (abs(lower) + abs(upper))
res = lower if res == upper else num
else:
total_length = abs(lower) + abs(upper)
if num < -total_length:
num += ceil(num / (-2 * total_length)) * 2 * total_length
if num > total_length:
num -= floor(num / (2 * total_length)) * 2 * total_length
if num > upper:
num = total_length - num
if num < lower:
num = -total_length - num
res = num * 1.0 # Make all numbers float, to be consistent
return res
|
def closest(l, n):
"""finds the closest number in sorted list l to n"""
mid = int(len(l) / 2)
if len(l) < 7:
return min(l, key=lambda e: abs(n - e))
elif n > l[mid]:
return closest(l[mid:], n)
else:
return closest(l[:mid+1], n)
|
def BuildCampaignCriterionOperations(campaign_operations):
"""Builds the operations needed to create Negative Campaign Criterion.
Args:
campaign_operations: a list containing the operations that will add
Campaigns.
Returns:
a list containing the operations that will create a new Negative Campaign
Criterion associated with each provided Campaign.
"""
criterion_operations = [
{
# The xsi_type of the operation can usually be guessed by the API
# because a given service only handles one type of operation.
# However, batch jobs process operations of different types, so
# the xsi_type must always be explicitly defined for these
# operations.
'xsi_type': 'CampaignCriterionOperation',
'operand': {
'xsi_type': 'NegativeCampaignCriterion',
'campaignId': campaign_operation['operand']['id'],
'criterion': {
'xsi_type': 'Keyword',
'matchType': 'BROAD',
'text': 'venus'
}
},
'operator': 'ADD'
}
for campaign_operation in campaign_operations]
return criterion_operations
|
def unique(errors, model, field, value, *, update=None):
"""Validates that a record's field is unique.
:param errors: The existing error map
:type errors: dict
:param model: The SQLAlchemy database model to check against
:type model: flask_sqlalchemy.Model
:param field: The model's property to check
:type field: sqlalchemy.orm.attributes.InstrumentedAttribute
:param value: The new value to check that must be unique
:param update: An existing instance of the record to stop false positive
:return: The updated errors map
:rtype: dict
"""
if value is not None and (update is None or
getattr(update, field.name) != value):
query = model.query.filter(field == value).first()
if query:
errors.setdefault(field.name, [])
errors[field.name].append("Value must be unique.")
return errors
|
def string(mat, val_format='{0:>8.3f}'):
""" Write a matrix to a string.
:param mat: matrix to form string with
:type mat: tuple(tuple(float))
:param precision: number of integers past decimal
:type precision: int
:rtype: str
"""
mat_str = ''
for row in mat:
mat_str += ''.join(val_format.format(val) for val in row)
mat_str += '\n'
mat_str = mat_str.rstrip()
return mat_str
|
def _customize_template(template, repository_id):
"""Copy ``template`` and interpolate a repository ID into its ``_href``."""
template = template.copy()
template['_href'] = template['_href'].format(repository_id)
return template
|
def duration(duration):
"""Filter that converts a duration in seconds to something like 01:54:01
"""
if duration is None:
return ''
duration = int(duration)
seconds = duration % 60
minutes = (duration // 60) % 60
hours = (duration // 60) // 60
s = '%02d' % (seconds)
m = '%02d' % (minutes)
h = '%02d' % (hours)
output = []
if hours > 0:
output.append(h)
output.append(m)
output.append(s)
return ':'.join(output)
|
def crimeValue(crimeStr):
"""Find the crime parameters in the .csv file and converts them from strings (str) to integers (int) for later comparison"""
if crimeStr == "low":
crimeInt = 1
elif crimeStr == "average":
crimeInt = 2
elif crimeStr == "high":
crimeInt = 3
else:
crimeInt = 0
return crimeInt
|
def with_unix_endl(string: str) -> str:
"""Return [string] with UNIX-style line endings"""
return string.replace("\r\n", "\n").replace("\r", "")
|
def get_pdb_atom_info(line):
"""Split and read pdb-file line (QPREP-OUT).
Extract and return:
atomnumber, atomname, resname, resid)
"""
# UNIT: check if the correct numbers are extracted
atomnum = int(line[6:11])
atmname = line[13:17].strip()
resname = line[17:20].strip()
resinum = int(line[22:27])
return (atomnum, atmname, resname, resinum)
|
def closeyear(year):
"""
Find how many years away was the closest leap year to a specific year
"""
return int(year % 4)
|
def sizeof_fmt(num, suffix='B', num_type='data'):
"""
Convert bytes into a human readable format
Straight rip from stackoverflow
"""
if num_type == 'data':
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Yi', suffix)
else:
if abs(num) < 1000:
return num
for unit in ['', 'K', 'M', 'B']:
if abs(num) < 1000.0:
return "%3.1f %s" % (num, unit)
num /= 1000.0
return "%.1f %s" % (num, 'T')
|
def is_ipv4_address(addr):
"""Return True if addr is a valid IPv4 address, False otherwise."""
if (not isinstance(addr, str)) or (not addr) or addr.isspace():
return False
octets = addr.split('.')
if len(octets) != 4:
return False
for octet in octets:
if not octet.isdigit():
return False
octet_value = int(octet)
if octet_value < 0 or octet_value > 255:
return False
return True
|
def _WrapBinaryOp(op_fn, retrieval_fn, value, ctx, item):
"""Wrapper for binary operator functions.
"""
return op_fn(retrieval_fn(ctx, item), value)
|
def keep_matched_keys(dict_to_modify,model_keys):
"""
Drops only the keys of a dict that do **not** have the same name as the keys in a source dictionnary.
Return dictionnary containing the rest.
Args:
dict_to_modify (TYPE): DESCRIPTION.
source_dict (TYPE): DESCRIPTION.
Returns:
modified_dict (TYPE): DESCRIPTION.
"""
if isinstance(model_keys, dict) :
model_keys = set(model_keys.keys())
return { kept_key : dict_to_modify[kept_key] for kept_key in model_keys if kept_key != 'empty' and dict_to_modify.get(kept_key) is not None}
|
def remove_dashes(dashed_date):
"""
remove the dashes from a 'yyyy-mm-dd' formatted date
write as a separate function because the apply(lambda x) one doesn't
work as expected
"""
return str(dashed_date).replace('-', '')
|
def hilbert_f(x):
"""The Hilbert transform of f."""
return x / (x ** 2 + 1)
|
def least_significant_bit(val):
""" Return the least significant bit
"""
return (val & -val).bit_length() - 1
|
def global_object_name(obj):
"""
Return full name of a global object.
>>> from scrapy import Request
>>> global_object_name(Request)
'scrapy.http.request.Request'
"""
return "%s.%s" % (obj.__module__, obj.__name__)
|
def _convert_bool_string(value):
"""
Convert a "True" or "False" string literal to corresponding boolean type.
This is necessary because Python will otherwise parse the string "False"
to the boolean value True, that is, `bool("False") == True`. This function
raises a ValueError if a value other than "True" or "False" is passed.
If the value is already a boolean, this function just returns it, to
accommodate usage when the value was originally inside a stringified list.
Parameters
----------
value : string {"True", "False"}
the value to convert
Returns
-------
bool
"""
if value in {"True", "False"}:
return value == "True"
elif isinstance(value, bool):
return value
else: # pragma: no cover
raise ValueError(f'invalid literal for boolean: "{value}"')
|
def capitalize(line):
"""
Courtesy of http://stackoverflow.com/questions/1549641/how-to-capitalize-the-first-letter-of-each-word-in-a-string-python
:param line:
:return:
"""
return ' '.join(s[0].upper() + s[1:] for s in line.split(' '))
|
def transpose_list(org_list):
"""
Transpose list of lists.
Parameters
----------
org_list : list
list of lists with equal lenghts.
Returns
-------
list :
transposed list.
"""
return list(map(list, zip(*org_list)))
|
def get_consumer_groups(acls):
"""
Given a list of plugins, filter out the `acl` plugin
and return a formatted string
of all the acl consumer group names which are `allowed`
to access the service.
"""
if acls is None:
return
return "`" + "`, `".join(i.get("group") for i in acls) + "`"
|
def get_param_val(
param_str,
param_key='',
case_sensitive=False):
"""
Extract numerical value from string information.
This expects a string containing a single parameter.
Parameters
==========
name : str
The string containing the information.
param_key : str (optional)
The string containing the label of the parameter.
case_sensitive : bool (optional)
Parsing of the string is case-sensitive.
Returns
=======
param_val : int or float
The value of the parameter.
See Also
========
set_param_val, parse_series_name
"""
if param_str:
if not case_sensitive:
param_str = param_str.lower()
param_key = param_key.lower()
if param_str.startswith(param_key):
param_val = param_str[len(param_key):]
elif param_str.endswith(param_key):
param_val = param_str[:-len(param_key)]
else:
param_val = None
else:
param_val = None
return param_val
|
def percental_difference_between_two_numbers(a, b):
"""
How much percent is smaller number smaller than bigger number.
If 1 -> both number equal size
If 0.5 -> smaller number is half the size of bigger number
"""
if a <= b:
return float(a) / b
else:
return float(b) / a
|
def is_natural(maybe_nat):
""" Check if the given item is an Int >= 0
:param maybe_nat: Any
:return: Boolean
"""
return isinstance(maybe_nat, int) and maybe_nat >= 0
|
def formatDollarsCents(d,noneValue='',zeroValue='$0.00'):
"""Formats a number as a dollar and cent value with alternatives for None and 0."""
if d is None:
return noneValue
elif d==0:
return zeroValue
return '${:.2f}'.format(d)
|
def sqrt(x: int) -> int:
"""
Gets the floor value of the positive square root of a number
"""
assert x >= 0
z = 0
if x > 3:
z = x
y = x // 2 + 1
while y < z:
z = y
y = (x // y + y) // 2
elif x != 0:
z = 1
return z
|
def get_trackdata(tracks):
"""Converts CVAT track data.
Args:
tracks (OrderedDict): CVAT track data
Returns:
dict: Data of all tracks
"""
trackdata, tracks_size = \
{}, {}
trackdata['tracks_number'] = len(tracks)
for id, track in enumerate(tracks):
tracks_size[id] = len(track['box'])
trackdata['tracks_size'] = tracks_size
return trackdata
|
def process_group(grp):
"""
Given a list of list of tokens
where each token starts with a
character from 'NSEWLRF', and
ends with a number, that describe
the motion of a ship and the direction
it faces at any given point in time,
compute the manhattan distance between
the initial point and the final point of
the ship.
:param grp: The list of list of tokens.
:return: The Manhattan distance between
the source and destination of the ship.
"""
dire = {"N": 0, "E": 0, "W": 0, "S": 0}
ship_dir_options = ["E", "S", "W", "N"]
current_dir_idx = 0
for elem in grp:
c, num = elem[0], int(elem[1:])
if c == "R":
current_dir_idx = (current_dir_idx + num // 90) % 4
elif c == "L":
current_dir_idx = (current_dir_idx - num // 90) % 4
elif c == "F":
dire[ship_dir_options[current_dir_idx]] += num
else:
dire[c] += num
dist_ver = abs(dire["N"] - dire["S"])
dist_hor = abs(dire["E"] - dire["W"])
man_dist = dist_ver + dist_hor
return man_dist
|
def find_du_based_on_ip(ip, functions):
"""
This method finds a du id associated to an ip
"""
for vnf in functions:
if 'vnfr' not in vnf.keys():
continue
vnfr = vnf['vnfr']
dus = []
if 'virtual_deployment_units' in vnfr.keys():
dus = vnfr['virtual_deployment_units']
if 'couldnative_deployment_units' in vnfr.keys():
dus = vnfr['cloudnative_deployment_units']
for du in dus:
du_string = str(du)
if ip in du_string:
return du['id'], vnf['id']
return None, None
|
def _str(text):
"""Convert from possible bytes without interpreting as number.
:param text: Input to convert.
:type text: str or unicode
:returns: Converted text.
:rtype: str
"""
return text.decode(u"utf-8") if isinstance(text, bytes) else text
|
def victoire_ligne(plateau, joueur):
"""
Teste si le plateau admet une victoire en ligne pour le joueur.
"""
for ligne in plateau:
if all(c == joueur for c in ligne):
return True
return False
|
def get_data(data_list, data_cache):
"""
Gets the data specified by the keys in the data_list from the data_cache
:param data_list: string or list of strings
:param data_cache: dictionary containing the stored data
:return: a single pandas.DataFrame if input is a string,
a list of DataFrames if the input is a list of strings
"""
if not isinstance(data_list, list):
data_list = [data_list]
tmp = [data_cache[d] for d in data_list]
if len(tmp) == 1:
return tmp[0]
res = ([t[0] for t in tmp], [t[1] for t in tmp])
return res
|
def build_SQL_query(query_words: dict) -> str:
"""
Builds an SQL style query string from a dictionary
where keys are column titles and values are values
that the query will test for.
Args:
query_words (dict): a dictionary where keys are column
titles and values are values
Returns:
str: an string that can be used as an SQL query
"""
query_string = ''
for col_nm, col_val in query_words.items():
if col_val not in [True, False]:
col_val = f"'{col_val}'"
query_string += f"{col_nm}=={col_val}"
if col_nm != list(query_words.keys())[-1]:
query_string += " & "
return query_string
|
def override_config(config, overrides):
"""Overrides config dictionary.
Args:
config: dict, user passed parameters for training job from JSON or
defaults.
overrides: dict, user passed parameters to override some within config
dictionary.
Returns:
Modified in-place config dictionary by overrides.
"""
for k, v in overrides.items():
if isinstance(v, dict):
config[k] = override_config(config.get(k, {}), v)
else:
config[k] = v
return config
|
def calc_split_class_average_iou(dict):
"""Calculate SOA-C-IoU-Top/Bot-40"""
num_img_list = []
for label in dict.keys():
num_img_list.append([label, dict[label]["images_total"]])
num_img_list.sort(key=lambda x: x[1])
sorted_label_list = [x[0] for x in num_img_list]
bottom_40_iou = 0
top_40_iou = 0
for label in dict.keys():
if sorted_label_list.index(label) < 40:
if dict[label]["iou"] is not None and dict[label]["iou"] >= 0:
bottom_40_iou += dict[label]["iou"]
else:
if dict[label]["iou"] is not None and dict[label]["iou"] >= 0:
top_40_iou += dict[label]["iou"]
bottom_40_iou /= 0.5*len(dict.keys())
top_40_iou /= 0.5*len(dict.keys())
return top_40_iou, bottom_40_iou
|
def format_list(_list):
"""Format a list to an enumeration.
e.g.: [a,b,c,d] -> a, b, c and d
"""
if len(_list) == 0:
return "no one"
elif len(_list) == 1:
return _list[0]
else:
s = ""
for e in _list[: len(_list) - 2]:
s = s + str(e) + ", "
s = s + str(_list[len(_list) - 2]) + " and " + str(_list[len(_list) - 1])
return s
|
def facility_name(hutch):
"""Return the facility name for an instrument"""
if hutch in [
'dia', 'mfx', 'mec', 'cxi', 'xcs', 'xpp', 'sxr', 'amo',
'DIA', 'MFX', 'MEC', 'CXI', 'XCS', 'XPP', 'SXR', 'AMO',
]:
return '{}_Instrument'.format(hutch.upper())
return '{}_Instrument'.format(hutch.lower())
|
def _calc_isbn10_check_digit(number):
"""Calculate the ISBN check digit for 10-digit numbers. The number passed
should not have the check bit included."""
check = sum((i + 1) * int(n)
for i, n in enumerate(number)) % 11
return 'X' if check == 10 else str(check)
|
def swap_xyz_string(xyzs, permutation):
"""
Permutate the xyz string operation
Args:
xyzs: e.g. ['x', 'y+1/2', '-z']
permuation: list, e.g., [0, 2, 1]
Returns:
the new xyz string after transformation
"""
if permutation == [0,1,2]:
return xyzs
else:
new = []
for xyz in xyzs:
tmp = xyz.replace(" ","").split(',')
tmp = [tmp[it] for it in permutation]
if permutation == [1,0,2]: #a,b
tmp[0] = tmp[0].replace('y','x')
tmp[1] = tmp[1].replace('x','y')
elif permutation == [2,1,0]: #a,c
tmp[0] = tmp[0].replace('z','x')
tmp[2] = tmp[2].replace('x','z')
elif permutation == [0,2,1]: #b,c
tmp[1] = tmp[1].replace('z','y')
tmp[2] = tmp[2].replace('y','z')
elif permutation == [1,2,0]: #b,c
tmp[0] = tmp[0].replace('y','x')
tmp[1] = tmp[1].replace('z','y')
tmp[2] = tmp[2].replace('x','z')
elif permutation == [2,0,1]: #b,c
tmp[0] = tmp[0].replace('z','x')
tmp[1] = tmp[1].replace('x','y')
tmp[2] = tmp[2].replace('y','z')
new.append(tmp[0] + ", " + tmp[1] + ", " + tmp[2])
return new
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.