content stringlengths 42 6.51k |
|---|
def render_operation_failures(failures):
"""
Renders the provided operation failures.
:param failures: failures to render
:return: rendered string
"""
result = '\n|\t'.join(failures)
return '\n|\t{}'.format(result) if result else '-' |
def _normalize_location(loc):
"""
Return a dictionary that represents the given location. If it's already a
dictionary it's returned as-is but if not we try different attributes to
get the latitude (``latitude`` or ``lat``) and longitude (``longitude``,
``lng``, or ``lon``).
"""
if isinstance(loc, dict):
return loc
d = {}
# Try different attributes for each one
guesses = {
"latitude": ("latitude", "lat"),
"longitude": ("longitude", "lng", "lon"),
}
for attr, ks in guesses.items():
for k in ks:
if hasattr(loc, k):
d[attr] = float(getattr(loc, k))
break
return d |
def get_human_readable_time(seconds: float) -> str:
"""Convert seconds into a human-readable string.
Args:
seconds: number of seconds
Returns:
String that displays time in Days Hours, Minutes, Seconds format
"""
prefix = "-" if seconds < 0 else ""
seconds = abs(seconds)
int_seconds = int(seconds)
days, int_seconds = divmod(int_seconds, 86400)
hours, int_seconds = divmod(int_seconds, 3600)
minutes, int_seconds = divmod(int_seconds, 60)
if days > 0:
time_string = f"{days}d{hours}h{minutes}m{int_seconds}s"
elif hours > 0:
time_string = f"{hours}h{minutes}m{int_seconds}s"
elif minutes > 0:
time_string = f"{minutes}m{int_seconds}s"
else:
time_string = f"{seconds:.3f}s"
return prefix + time_string |
def calc_pid(seq1, seq2):
"""
Calculates the percentage ID (still as a decimal)
between two sequences.
Parameters
----------
seq1: str
seq2: str
Returns
-------
pid: float
"""
alnlen = len(seq1)
identical = 0
for i in range(0, len(seq1)):
if seq1[i].isalpha() and seq2[i].isalpha() and seq1[i] == seq2[i]:
identical += 1
pid = identical/alnlen
return pid |
def is_transmitter(metric):
"""Is interface ``metric`` a transmitter?
:param dict metric: The metric.
:rtype: :py:class:`bool`
"""
return metric.get("name", "").endswith("tx") |
def add_extension_if_needed(filepath, ext):
"""Add the extension ext to fpath if it doesn't have it.
Parameters
----------
filepath: str
File name or path
ext: str
File extension
Returns
-------
filepath: str
File name or path with extension added, if needed.
"""
if not filepath.endswith(ext):
filepath += ext
return filepath |
def label_match(l1, l2):
""" for two sequences with different length,
return whether the short one matches the long one(is a substring) """
l1, l2 = list(l1), list(l2)
if len(l1) > len(l2):
l1, l2 = l2, l1
now = -1
for k in l1:
try:
now = l2.index(k, now + 1)
except:
return False
return True |
def normalize_slots(slots):
"""Slot manipulation library
This function "normalizes" a list of slots by merging all consecutive or
overlapping slots into non-overlapping ones. IMPORTANT: the input slots
array has to be sorted by initial datetime of the slot, this is, for a
given slot at position 'i', it is always met the following condition:
slots[i]['starting_date'] <= slots[i+1]['starting_date'].
:param slots: The list of slots to be normalized.
:return: The normalized list of slots.
"""
if slots is None:
return []
slots_n = len(slots)
if slots_n < 2:
return slots
normalized_s = []
s = slots[0]
t = slots[1]
s_i = 0
t_i = 1
while s_i < slots_n:
if s[1] < t[0]:
# ### CASE A
normalized_s.append(s)
s = t
if (s[0] <= t[0]) and (s[1] <= t[1]):
# ### CASE B
s = (s[0], t[1])
# ### CASE C and next iteration
if t_i < (slots_n - 1):
t_i += 1
t = slots[t_i]
continue
else:
# ### last vectors
normalized_s.append(s)
break
return normalized_s |
def isTernary(string):
"""
check if given compound is a ternary
"""
str1 = string.split('_')[0]
nonumber=''
for s in str1:
if s=='.':
return False
if s.isdigit():
nonumber=nonumber+' '
else:
nonumber=nonumber+s
if len(nonumber.split())==3:
return True
return False |
def histogram(s):
"""to check s in string"""
d={}
for c in s:
d[c]=1+d.get(c,0)
return d |
def _check_available_port(port, ipv6=True):
""" True -- it's possible to listen on this port for TCP/IPv4 or TCP/IPv6
connections. False -- otherwise.
"""
import socket
# noinspection PyBroadException
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', port))
sock.listen(1)
sock.close()
if ipv6:
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
sock.bind(('::1', port))
sock.listen(1)
sock.close()
except Exception:
return False
return True |
def _remove_illegal_chars(x) -> str:
"""
Remove illegal quote characters
Parameters
----------
x: str
Returns
-------
str
"""
return x.replace("\\\\", "").replace('"', "") |
def update_markup(markup, field_id, new_name=None):
"""Helper function to find and rename or delete value from markup"""
if isinstance(markup, list):
# this is a sequence item so we look at the 'sub_rules' if they exist
for row in markup:
if 'sub_rules' in row:
return update_markup(row['sub_rules'], field_id, new_name)
elif isinstance(markup, dict):
# this is a standard rule so we look at this one itself
siblings = []
update_name = None
update_id = None
for name in markup:
if 'rule_id' in markup[name] and markup[name]['rule_id'] == field_id:
update_name = name
elif 'sub_rules' in markup[name]:
update_id = update_markup(markup[name]['sub_rules'], field_id, new_name)
if update_id:
return update_id
elif 'sequence' in markup[name]:
update_id = update_markup(markup[name]['sequence'], field_id, new_name)
if update_id:
return update_id
else:
siblings.append(name)
if update_name:
if new_name:
if new_name not in siblings:
update_id = field_id
else:
markup.pop(update_name)
update_id = field_id
return update_id |
def _level_parse(level):
"""Parse levels as integers, or the string 'surface'"""
if level == "surface":
return str(level)
else:
return int(level) |
def ddmmss_to_deg(position):
"""
Converts positions in deg:min:sec format to fractional degrees.
input:
------
position: str
Position in deg:min:sec format.
output:
-------
position_deg: float
Position in fractional degrees.
"""
split_position = position.split(":")
# Check if positive or negative:
if float(split_position[0]) <= 0:
if len(split_position) == 3:
position_deg = float(split_position[0]) - (
float(split_position[1])/60. + float(split_position[2])/3600.)
else:
position_deg = float(split_position[0]) - (
float(split_position[1])/60.)
else:
if len(split_position) == 3:
position_deg = float(split_position[0]) + (
float(split_position[1])/60. + float(split_position[2])/3600.)
else:
position_deg = float(split_position[0]) + (
float(split_position[1])/60.)
return position_deg |
def consecutive_seconds(rel_seconds, window_size_sec, stride_sec=1):
"""
Function:
return a list of all the possible [window_start, window_end] pairs containing consecutive seconds of length window_size_sec inside.
Args:
rel_seconds: a list of qualified seconds
window_size_sec: int
stride_sec: int
Returns:
win_start_end: a list of all the possible [window_start, window_end] pairs that meets the requirement.
Test:
>>> rel_seconds = [2,3,4,5,6,7,9,10,11,12,16,17,18]; window_size_sec = 3; stride_sec = 1
>>> print(consecutive_seconds(rel_seconds, window_size_sec))
>>> [[2, 4], [3, 5], [4, 6], [5, 7], [9, 11], [10, 12], [16, 18]]
"""
win_start_end = []
for i in range(0, len(rel_seconds) - window_size_sec + 1, stride_sec):
if rel_seconds[i + window_size_sec - 1] - rel_seconds[i] == window_size_sec - 1:
win_start_end.append([rel_seconds[i], rel_seconds[i + window_size_sec - 1]])
return win_start_end |
def url_add_api_key(url_dict: dict, api_key: str) -> str:
"""Attaches the api key to a given url
Args:
url_dict: Dict with the request url and it's relevant metadata.
api_key: User's API key provided by US Census.
Returns:
URL with attached API key information.
"""
return (url_dict['url']+f'&key={api_key}').replace(' ', '%20') |
def get_coverage_per_file(target_cov):
"""Returns the coverage per file within |target_cov|."""
return target_cov['data'][0]['files'] |
def all_of_type(objects, type):
"""Return all objects that are instances of a given type.
"""
return [o for o in objects if isinstance(o, type)] |
def navigate_indexed_path(source, path_):
""" """
parts = path_.split("[")
p_ = parts[0]
index = int(parts[1][:-1])
value = source.get(p_, None)
if value is None:
return value
try:
return value[index]
except IndexError:
return None |
def lower(text):
"""Returns text that has been lower.
Args:
text (str): input text to process.
Output:
result (str): corresponding text which has been lower.
"""
return text.lower() |
def as_list(val):
"""return a list with val if val is not already a list, val otherwise"""
if isinstance(val, list):
return val
else:
return [val] |
def ode(x,r,xc):
"""
Compute the slope of a coordinate in an circle
Params:
x = the coordinate of desire slop
r = radius of the slope
xc = x coordinate of the center
return:
slop of at the coordinate provided
"""
return -(r**2 - (x - xc)**2)**(-0.5)*(-1.0*x + 1.0*xc)
#%%
|
def format_tqdm_metric(value: float, best_value: float, fmt: str) -> str:
"""Formats a value to display in tqdm."""
if value == best_value:
return (fmt + '*').format(value)
return (fmt + ' (' + fmt + '*)').format(value, best_value) |
def move_names_to_the_end(names, names_to_move_to_the_end):
"""
Remove the items of ``names_to_move_to_the_end`` from ``names``
and append to the right of names
>>> names = ['a','c','d','e']
>>> names_to_move_to_the_end = ['c','e']
>>> move_names_to_the_end(names, names_to_move_to_the_end)
['a', 'd', 'c', 'e']
>>> names_to_move_to_the_end = 'c e'
>>> move_names_to_the_end(names, names_to_move_to_the_end)
['a', 'd', 'c', 'e']
"""
if isinstance(names_to_move_to_the_end, str):
names_to_move_to_the_end = names_to_move_to_the_end.split()
else:
names_to_move_to_the_end = list(names_to_move_to_the_end)
removed = [x for x in names if x not in names_to_move_to_the_end]
return list(removed) + names_to_move_to_the_end |
def time_to_text(seconds):
"""
This function converts a time in seconds into a reasonable format.
Parameters
----------
seconds : float
Time in seconds.
Returns
-------
time_as_text: str
Time in s, min, h, d, weeks or years depending on input.
"""
if seconds > 60:
if seconds > 3600:
if seconds > 86400:
if seconds > 1209600:
if seconds > 62899252:
time_as_text = 'years'
else:
time_as_text = '{} weeks'.format(round(seconds / 1209600, 1))
else:
time_as_text = '{} d'.format(round(seconds / 86400, 1))
else:
time_as_text = '{} h'.format(round(seconds / 3600, 1))
else:
time_as_text = '{} min'.format(round(seconds / 60, 1))
else:
time_as_text = '{} s'.format(int(seconds))
return time_as_text |
def _get_usb_hub_map(device_info_list):
"""Creates a map of usb hub addresses to device_infos by port.
Args:
device_info_list (list): list of known usb_connections dicts.
Returns:
dict: map of usb hub addresses to device_infos by port
"""
map_usb_hub_ports = {}
for device_info in device_info_list:
hub_address = device_info['usb_hub_address']
port = device_info['usb_hub_port']
if hub_address:
if hub_address not in map_usb_hub_ports:
map_usb_hub_ports[hub_address] = {}
if not map_usb_hub_ports[hub_address].get(
port) or device_info['ftdi_interface'] == 2:
map_usb_hub_ports[hub_address][port] = device_info
return map_usb_hub_ports |
def _decode_config(c, num_variables):
"""inverse of _serialize_config, always converts to spin."""
def bits(c):
n = 1 << (num_variables - 1)
for __ in range(num_variables):
yield 1 if c & n else -1
n >>= 1
return tuple(bits(c)) |
def isprime(number):
"""
Check if a number is a prime number
:type number: integer
:param number: The number to check
"""
if number == 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True |
def primary_beam_shape_tag_from_primary_beam_shape_2d(primary_beam_shape_2d):
"""Generate an image psf shape tag, to customize phase names based on size of the image PSF that the original PSF \
is trimmed to for faster run times.
This changes the phase name 'phase_name' as follows:
image_psf_shape = 1 -> phase_name
image_psf_shape = 2 -> phase_name_image_psf_shape_2
image_psf_shape = 2 -> phase_name_image_psf_shape_2
"""
if primary_beam_shape_2d is None:
return ""
else:
y = str(primary_beam_shape_2d[0])
x = str(primary_beam_shape_2d[1])
return "__pb_" + y + "x" + x |
def _check_filepath(filepath):
"""
Validate if the filepath attr/arg is a str
:param str filepath: object to validate
:return str: validated filepath
:raise TypeError: if the filepath is not a string
"""
# might be useful if we want to have multiple locked paths in the future
# def _check_string(obj):
# """ check if object is a string or a list of strings """
# return bool(obj) and all(isinstance(elem, str) for elem in obj)
if not isinstance(filepath, str):
raise TypeError("No valid filepath provided. It has to be a str, "
"got: {}".format(filepath.__class__.__name__))
return filepath |
def hamming_distance(s1, s2):
"""Returns the Hamming distance between two equal-length sequences"""
if len(s1) != len(s2):
raise ValueError("Sequences of unequal length")
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) |
def log(message, *values):
"""
log
:param message:
:param values:
:return:
"""
if not values:
print(message)
else:
values_str = ', '.join(str(x) for x in values)
print('{0}: {1}'.format(message, values_str))
return True |
def format_ip_int(data: dict):
"""Collapse napalm ip_interface output to:
{
{{ Interface }}:
ipv4_address: {{ IP }},
ipv6_address: {{ IP }}
}
"""
output = {}
for k, v in data.items():
ip_dict = {}
for i in range(4, 7, 2):
ip = v.get(f"ipv{i}")
if ip:
address = next(iter(ip))
ip_dict.update(
{f"ipv{i}_address": f"{address}/{ip[address]['prefix_length']}"}
)
output.update({k: ip_dict})
return output |
def first_sentence(str):
"""
Return the first sentence of a string - everything up to the period,
or the whole text if there is no period.
>>> first_sentence('')
''
>>> first_sentence('Incomplete')
''
>>> first_sentence('The first sentence. This is ignored.')
'The first sentence.'
"""
return str[0:str.find('.') + 1] |
def read_any_text_file(file_name):
"""
This function trys to read and text file and return its contents.
:param file_name: The file to read. If the file isn't in the same directory as this program, you'll need to enter
the full path, i.e. /home/username/path/to/file or drive_letter:\\full\\path\\to\\file
:return: File contents, if possible.
"""
try:
whole_file = None
with open(file_name, "r") as fh:
# for line in fh:
# print(line.strip())
whole_file = fh.read()
return whole_file
except Exception as e:
print(f"Something bad happened when trying to read {file_name}.\nI can't return anything.\n{e}")
return None |
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, nothing at this URL.', 404 |
def undistort_halcon_polynomial(u_tilde, v_tilde, k1, k2, k3, p1, p2):
"""
From the HALCON Docs:
The polynomial model uses three parameters () to model
the radial distortions and two parameters () to model
the decentering distortions.
The following equations transform the distorted image
plane coordinates into undistorted image plane coordinates
if the polynomial model is used:
These equations cannot be inverted analytically. Therefore,
distorted image plane coordinates must be calculated from
undistorted image plane coordinates numerically.
k1=k2=k3=p1=p2=0 means no distortion.
"""
u_tilde_to_2 = u_tilde**2
v_tilde_to_2 = v_tilde**2
r_to_2 = u_tilde_to_2 + v_tilde_to_2
r_to_4 = r_to_2**2
r_to_6 = r_to_4 * r_to_2
temp1 = k1 * r_to_2
temp1 += k2 * r_to_4
temp1 += k3 * r_to_6
u = u_tilde + u_tilde * temp1 # the radial part
v = v_tilde + v_tilde * temp1
uv_tilde = u_tilde * v_tilde
u += p1 * (r_to_2 + 2 * u_tilde_to_2) + 2 * p2 * uv_tilde # The tilt part
v += 2 * p1 * uv_tilde + p2 * (r_to_2 + 2 * v_tilde_to_2)
return u,v |
def __heuristic(a, b):
"""
The heuristic for A* Grid search
"""
return sum(abs(ai - bi) for ai, bi in zip(a, b)) |
def make_rule_key(prefix, rule, group_id, cidr_ip):
"""Creates a unique key for an individual group rule"""
if isinstance(rule, dict):
proto, from_port, to_port = [rule.get(x, None) for x in ('proto', 'from_port', 'to_port')]
# fix for 11177
if proto not in ['icmp', 'tcp', 'udp'] and from_port == -1 and to_port == -1:
from_port = 'none'
to_port = 'none'
else: # isinstance boto.ec2.securitygroup.IPPermissions
proto, from_port, to_port = [getattr(rule, x, None) for x in ('ip_protocol', 'from_port', 'to_port')]
key = "%s-%s-%s-%s-%s-%s" % (prefix, proto, from_port, to_port, group_id, cidr_ip)
return key.lower().replace('-none', '-None') |
def tupilate(source, val):
"""Broadcasts val to be a tuple of same size as source"""
if isinstance(val, tuple):
assert(len(val) == len(source))
return val
else:
return (val,)*len(source) |
def safe_string(o):
"""This will make string out of ANYTHING without having to worry about the stupid Unicode errors
This function tries to make str/unicode out of ``o`` unless it already is one of those and then
it processes it so in the end there is a harmless ascii string.
Args:
o: Anything.
"""
if not isinstance(o, str):
o = str(o)
if isinstance(o, bytes):
o = o.decode("utf-8", "ignore")
o = o.encode("ascii", "xmlcharrefreplace").decode("ascii")
return o |
def get_logs_url(build_id, project_id='oss-fuzz-base'):
"""Returns url that displays the build logs."""
url_format = ('https://console.developers.google.com/logs/viewer?'
'resource=build%2Fbuild_id%2F{0}&project={1}')
return url_format.format(build_id, project_id) |
def gradients_for_var_group(var_groups, gradients, name):
"""Returns a slice of `gradients` belonging to the var group `name`."""
start = 0
for group_name in sorted(var_groups.keys()):
n = len(var_groups[group_name])
if group_name == name:
return gradients[start:start+n]
start += n
return [] |
def versionStrToTuple(versionStr):
""" Converts a version string to tuple
E.g. 'x.y.z' to (x, y, x)
"""
versionInfo = []
for elem in versionStr.split('.'):
try:
versionInfo.append(int(elem))
except:
versionInfo.append(elem)
return tuple(versionInfo) |
def unit_sort(text):
"""
A function to sort files when timepoints are encoded within the filename
using common abbreviations.
Parameters:
text (str): filename e.g. (proteinX_100ns)
Returns:
Tuple(int, text): for sorting files
"""
if text.startswith("-"):
return 0, text
elif text.endswith("ns"):
return 1, text
elif text.endswith("us"):
return 2, text
elif text.endswith("ms"):
return 3, text |
def remove_smallest(nums):
"""Remove smallest integer from list of integers.
input = integers, in list
output = integers, in list, missing the smallest value
ex. [1,2,3,4,5] = [2,3,4,5]
ex. [5,3,2,1,4] = [5,3,2,4]
ex. [2,2,1,2,1] = [2,2,2,1]
"""
if not nums:
return []
output = nums[0]
new_nums = nums[::]
for num in new_nums:
if num < output:
output = num
# while len(new_nums) == len(nums):
for i in range(len(new_nums)):
if new_nums[i] == output:
new_nums.remove(new_nums[i])
break
return new_nums |
def target_glucose_value(
percent_effect_duration,
min_value,
max_value
):
""" Computes a target glucose value for a correction, at a given time
during the insulin effect duration
Arguments:
percent_effect_duration -- percent of time elapsed of the insulin
effect duration
min_value -- minimum (starting) target value
max_value -- maximum (starting) target value
Output:
A target value somewhere between the minimum and maximum (inclusive)
"""
# The inflection point in time: before it we use minValue,
# after it we linearly blend from minValue to maxValue
use_min_value_until_percent = 0.5
if percent_effect_duration <= use_min_value_until_percent:
return min_value
if percent_effect_duration >= 1:
return max_value
slope = (
(max_value - min_value) /
(1 - use_min_value_until_percent)
)
return min_value + slope * (percent_effect_duration
- use_min_value_until_percent
) |
def get_risk(rising, rel_level):
"""Determines the threat level from relative level and whether it is rising or falling"""
if rel_level >= 1 and rising or rel_level >= 1.5:
threat = "Severe"
elif rel_level >= 0.75 and rising or rel_level >=1 and not rising:
threat = "High"
elif rel_level >= 0.75 and not rising or rel_level >= 0.5 and rising:
threat = "Moderate"
else:
threat = "Low"
return threat |
def irm(target, interference):
"""Compute ideal ratio mask (IRM)"""
mask = target / (target + interference)
return mask |
def remove_every_other(lst):
"""Return a new list of other item.
>>> lst = [1, 2, 3, 4, 5]
>>> remove_every_other(lst)
[1, 3, 5]
This should return a list, not mutate the original:
>>> lst
[1, 2, 3, 4, 5]
"""
return lst[::2] |
def convert_bytes(bytes):
"""Returns given bytes as prettified string."""
bytes = float(bytes)
if bytes >= 1099511627776:
terabytes = bytes / 1099511627776
size = '%.2fT' % terabytes
elif bytes >= 1073741824:
gigabytes = bytes / 1073741824
size = '%.2fG' % gigabytes
elif bytes >= 1048576:
megabytes = bytes / 1048576
size = '%.2fM' % megabytes
elif bytes >= 1024:
kilobytes = bytes / 1024
size = '%.2fK' % kilobytes
else:
size = '%.2fb' % bytes
return size |
def rk4(y, x, dx, f):
"""computes 4th order Runge-Kutta for dy/dx.
y is the initial value for y
x is the initial value for x
dx is the difference in x (e.g. the time step)
f is a callable function (y, x) that you supply to
compute dy/dx for the specified values.
"""
k1 = dx * f(y, x)
k2 = dx * f(y + 0.5*k1, x + 0.5*dx)
k3 = dx * f(y + 0.5*k2, x + 0.5*dx)
k4 = dx * f(y + k3, x + dx)
return y + (k1 + 2*k2 + 2*k3 + k4) / 6. |
def escape(s):
"""
Replace potential special characters with escaped version.
For example, newline => \\n and tab => \\t
"""
return s.replace('\n', '\\n').replace('\t', '\\t').replace('\r', '\\r') |
def format_dtype(form_data, key, dtype):
"""
"""
if key not in form_data:
return None
try:
res = dtype(form_data[key])
except:
return None
return res |
def generate_jmespath(text: str, name_contains_array: str) -> str:
"""
Helper function to generate a bit of jmespath.org code.
Example:
```python
reference = "contains(labels, 'hi') && contains(labels, 'there')"
assert generate_jmespath("hi, there", 'labels') == reference
assert generate_jmespath("hi", 'labels') == "contains(labels, 'hi')"
```
"""
raw_items = text.split(",")
items = []
for item in raw_items:
item = item.strip()
item = f"contains({name_contains_array}, '{item}')"
items.append(item)
return " && ".join(items) |
def make_sid_cookie(sid, uri):
"""Given a sid (from a set-cookie) figure out how to send it back"""
# sometime near 0.92, port got dropped...
# uritype, uribody = urllib.splittype(uri)
# host, path = urllib.splithost(uribody)
# host, port = urllib.splitnport(host)
# if port == -1:
# port = dict(http=80, https=443)[uritype] # we want to throw here
cookiename = "JIFTY_SID_HIVEMINDER"
return "%s=%s" % (cookiename, sid) |
def interval_to_milliseconds(interval):
"""Convert a Binance interval string to milliseconds
:param interval: Binance interval string, e.g.: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w
:type interval: str
:return:
int value of interval in milliseconds
None if interval prefix is not a decimal integer
None if interval suffix is not one of m, h, d, w
"""
seconds_per_unit = {
"m": 60,
"h": 60 * 60,
"d": 24 * 60 * 60,
"w": 7 * 24 * 60 * 60,
}
try:
return int(interval[:-1]) * seconds_per_unit[interval[-1]] * 1000
except (ValueError, KeyError):
return None |
def CORMSE(X,Y):
""" caculate the RMSE of X and Y """
import math
num=len(X)
if len(X)!=len(Y) or len(X)==0:
print ("list X and list Y have different length!")
RMSE=9999.0
return RMSE
else:
wucha=0.0
for i in range(num):
wucha=wucha+ math.pow((X[i]-Y[i]),2)
RMSE=math.sqrt(wucha/num)
return RMSE |
def add_timestamps(configs, timestamps_dict):
"""For each config, set its timestamp_format field based on its timestamp_format_key field."""
for config in configs:
config["timestamp_format"] = timestamps_dict[config["timestamp_format_key"]]
return configs |
def BitmaskBool(bitmask, value):
"""Returns True or False depending on whether a particular bit has been set.
Microsoft uses bitmasks as a compact way of denoting a number of boolean
settings. The second bit, for example, might be the ADS_UF_ACCOUNTDISABLE
bit, so if the second bit is a 1, then the account is disabled, and if it is
a 0, then it is not.
As an example, to create the 'disabled' property of a User object, we use the
userAccountControl property and ADS_UF_ACCOUNTDISABLE constant.
BitmaskBool(user.user_account_control, constants.ADS_UF_ACCOUNTDISABLE)
This will return True if the bit is set in user.user_account_control.
Args:
bitmask: a number representing a bitmask
value: the value to be checked (usually a known constant)
Returns:
True if the bit has been set, False if it has not.
"""
if int(bitmask) & int(value):
return True
else:
return False |
def _detect_replacing_tx_low_gas_price_parity(message):
"""source:
https://github.com/paritytech/parity/blob/1cd93e4cebeeb7b14e02b4e82bc0d4f73ed713d9/rpc/src/v1/helpers/errors.rs#L316
"""
return message.startswith("Transaction gas price is too low") |
def four_digit_range(s, lo, hi):
"""Return True if s is a 4 digit number string in range of lo-hi (inclusive)"""
if len(s) != 4:
return False
return int(s) in range(lo, hi + 1) |
def oscar_calculator(wins: int) -> float:
""" Helper function to modify rating based on the number of Oscars won. """
if 1 <= wins <= 2:
return 0.3
if 3 <= wins <= 5:
return 0.5
if 6 <= wins <= 10:
return 1.0
if wins > 10:
return 1.5
return 0 |
def egcd(a, b):
"""
Extended Euclidean Algorithum
"""
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y) |
def type_check(obj: object, type_name: str) -> bool:
"""
circulation dependency problems can be resolved by TYPE_CHECKING,
but this can not resolve NO type linting problems. eg:
if isinstance(msg, Contact):
pass
in this problem, program don't import Contact at running time. So, it will
throw a Exception, which will not be threw
:param obj:
:param type_name:
:return:
"""
if hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
return obj.__class__.__name__ == type_name
return False |
def mac_from_ip(ip_address):
"""Create a MAC address based on the provided IP.
Algorithm:
- the first 2 bytes are fixed to 06:00
- the next 4 bytes are the IP address
Example of function call:
mac_from_ip("192.168.241.2") -> 06:00:C0:A8:F1:02
C0 = 192, A8 = 168, F1 = 241 and 02 = 2
:param ip_address: IP address as string
:return: MAC address from IP
"""
mac_as_list = ['06', '00']
mac_as_list.extend(
list(
map(
lambda val: '{0:02x}'.format(int(val)),
ip_address.split('.')
)
)
)
return "{}:{}:{}:{}:{}:{}".format(*mac_as_list) |
def nvl(value, default):
""" Evaluates if value es empty or None, if so returns default
Parameters:
value: the evalue to evaluate
default: the default value
Returns:
value or default
"""
if value:
return value
return default |
def bool_flag(s):
"""Helper function to make argparse work with the input True and False.
Otherwise it reads it as a string and is always set to True.
:param s: string input
:return: the boolean equivalent of the string s
"""
if s == '1' or s == 'True':
return True
elif s == '0' or s == 'False':
return False
msg = 'Invalid value "%s" for bool flag (should be 0, False or 1, True)'
raise ValueError(msg % s) |
def prepare_data(text):
"""
Prepare data
"""
labels = [t.split()[0] for t in text]
labels = [l.split(':')[0] for l in labels]
X = [t.split()[1:] for t in text]
X = [' '.join(t) for t in X]
return X, labels |
def get_relative_name(task_list, bug_id, current_name):
"""Convert a name to a relative name."""
for task in task_list:
if current_name.endswith("!"):
new_current_name = "%sbug_%i" % (current_name, task.bug_id)
else:
new_current_name = "%s.bug_%i" % (current_name, task.bug_id)
if task.bug_id == bug_id:
return new_current_name
relative_name = get_relative_name(
task.task_list,
bug_id,
new_current_name
)
if relative_name != "":
return relative_name
return "" |
def row_multiply(matrix, row, factor):
"""
Multiplies a row by a factor
:param matrix: List of lists of equal length containing numbers
:param row: index of a row
:param factor: multiplying factor
:return: List of lists of equal length containing numbers
"""
matrix[row] = [i*factor for i in matrix[row]]
return matrix |
def std(vals):
"""Computes the standard deviation from a list of values."""
n = len(vals)
if n == 0:
return 0.0
mu = sum(vals) / n
if mu == 1e500:
return NotImplemented
var = 0.0
for val in vals:
var = var + (val - mu)**2
return (var / n)**0.5 |
def clean_url_fragment(f):
"""
Args:
- f: (str)
Returns: (str)
"""
return f.strip('/') |
def problem48(limit):
"""Problem 48 - Self powers"""
# Lazy
result = 0
for x in range(1, limit + 1):
result += x ** x
return int(str(result)[-10:]) |
def build_iterator(obj_x, obj_y):
"""Build a cross-tabulated iterator"""
l = []
for x in obj_x:
for y in obj_y:
l.append((x, y))
return l |
def afill(start, end, ntries):
"""A function that fill evenly spaced values between two numbers"""
step = (end-start)/float(ntries+1) if ntries > 0 else 0
final_list = [float(start) + (i+1)*step for i in range(ntries)]
return(final_list) |
def count_genes(person, one_gene, two_genes):
"""
Subfunction within joint_probability and update to count the number of copies
of the gene of interest that a given person carries.
"""
if person in one_gene:
return 1
elif person in two_genes:
return 2
else:
return 0 |
def _is_null_msg(dialect, msg, field_name):
"""
easier unit testing this way
"""
if dialect == 'mssql':
if 'Cannot insert the value NULL into column \'%s\'' % field_name in msg:
return True
elif dialect == 'sqlite':
if '.%s may not be NULL' % field_name in msg:
return True
elif dialect == 'postgresql':
if 'null value in column "%s" violates not-null constraint' % field_name in msg:
return True
else:
raise ValueError('is_null_exc() does not yet support dialect: %s' % dialect)
return False |
def smart_truncate(text, max_length=100, suffix='...'):
"""
Returns a string of at most `max_length` characters, cutting
only at word-boundaries. If the string was truncated, `suffix`
will be appended.
"""
if text is None:
return ''
# Return the string itself if length is smaller or equal to the limit
if len(text) <= max_length:
return text
# Cut the string
value = text[:max_length]
# Break into words and remove the last
words = value.split(' ')[:-1]
# Join the words and return
return ' '.join(words) + suffix |
def string_dist(s1, s2, wildcard = "N", letters = ["A","T","C","G"]):
"""
compute the hamming distance between two aligned strings with wildcards
Arguments
----------
s1: the first string
s2: the second string
wildcard: the letter of the wildcard
s1 and s2 should be of the same length and their positions should be aligned.
A wildcard does not count into the the calculation of the distance.
Returns
----------
int distance
"""
dist = 0
for i, j in zip(s1, s2):
if (i != wildcard and j != wildcard and i in letters and j in letters and i!=j):
dist += 1
return dist |
def memoize(n):
"""
:type n: int
:rtype: int
"""
cache = {0: 0, 1: 1}
for i in range(2, n+1):
cache[i] = cache[i-1] + cache[i-2]
return cache[n] |
def _equalsIgnoreCase(a, b):
"""
Return true iff a and b have the same lowercase representation.
>>> _equalsIgnoreCase('dog', 'Dog')
True
>>> _equalsIgnoreCase('dOg', 'DOG')
True
"""
return a == b or a.lower() == b.lower() |
def find_insertion_point(list_, i):
"""
Return the index where list_[i] belongs in list_[:i + 1].
@param list list_: list to find insertion point in
@param int i: index of element to insert
@rtype: int
>>> find_insertion_point([1, 3, 2], 2 )
1
"""
v = list_[i]
while i > 0 and list_[i - 1] > v:
i -= 1
return i |
def apply_velocities(pos, vels):
"""applies velocities by adding velocity to the position for each moon in
each dimension
"""
for i, moon_position in enumerate(pos):
for dimmension, _ in enumerate(moon_position):
moon_position[dimmension] += vels[i][dimmension]
return pos |
def payables_turnover(purchases, average_trade_payables):
"""Computes payables turnover.
Parameters
----------
purchases : int or float
Purchases
average_trade_payables : int or float
Average trade payables
Returns
-------
out : int or float
Purchases turnover
"""
return purchases / average_trade_payables
def number_of_days_of_payables(number_of_days, payables_turnover):
"""Computes number of days of payables.
Parameters
----------
number_of_days : int or float
Number of days in period
payables_turnover : int or float
Payables turnover
Returns
-------
out : int or float
Number of days of payables
"""
return number_of_days / payables_turnover
def working_capital_turnover(revenue, average_working_capital):
"""Computes working capital turnover.
Parameters
----------
revenue : int or float
Revenue
average_working_capital : int or float
Average working capital in period
Returns
-------
out : int or float
Working capital turnover
"""
return revenue / average_working_capital |
def mcd(a: int,
b: int) -> int:
"""This function returns the greatest common divisor from a and b.
Args:
a (int): dividend.
b (int): divider.
Returns:
int: the GCD from a and b.
"""
if a % b == 0:
return b
return mcd(b, a % b) |
def font_stretch(keyword):
"""``font-stretch`` descriptor validation."""
return keyword in (
'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed',
'normal',
'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded') |
def farenheit(ctemp):
""" Convert celcius to farenheit."""
return round(9.0/5.0 * ctemp + 32) |
def calc_RMM_phase(RMM1, RMM2, amp_thresh=0):
"""
Given RMM1 and RMM2 indices, calculate MJO phase.
Provided by Zane K. Martin (CSU).
Args:
RMM1: EOF for MJO phase space diagram.
RMM2: EOF for MJO phase space diagram.
amp_thresh (int): MJO amplitude threshold. Defaults to 0.
"""
if (RMM1**2 + RMM2**2 > amp_thresh) and (RMM2 < 0) and (RMM2 > RMM1):
phase = 1
elif (RMM1**2 + RMM2**2 > amp_thresh) and (RMM1 < 0) and (RMM2 < RMM1):
phase = 2
elif (RMM1**2 + RMM2**2 > amp_thresh) and (RMM1 > 0) and (RMM2 < -RMM1):
phase = 3
elif (RMM1**2 + RMM2**2 > amp_thresh) and (RMM2 < 0) and (RMM2 > -RMM1):
phase = 4
elif (RMM1**2 + RMM2**2 > amp_thresh) and (RMM2 > 0) and (RMM2 < RMM1):
phase = 5
elif (RMM1**2 + RMM2**2 > amp_thresh) and (RMM1 > 0) and (RMM2 > RMM1):
phase = 6
elif (RMM1**2 + RMM2**2 > amp_thresh) and (RMM1 < 0) and (RMM2 > -RMM1):
phase = 7
elif (RMM1**2 + RMM2**2 > amp_thresh) and (RMM2 > 0) and (RMM2 < -RMM1):
phase = 8
else:
phase = 0
return(phase) |
def get_current_categories(request, object):
"""Returns all current categories based on given request. Current
categories are the current selected category and all parent categories of
it.
"""
if object and object.content_type == "category":
parents = object.get_parents()
current_categories = [object]
current_categories.extend(parents)
elif object and object.content_type == "product":
current_categories = []
category = object.get_current_category(request)
while category:
current_categories.append(category)
category = category.parent
else:
current_categories = []
return current_categories |
def substitute_params(sql, sql_params):
"""
Substitute SQL dict of parameter values
Args:
sql : sql statement
sql_params : dict of parameters to substitute
Returns:
string containing SQL with parameters substituted in
"""
for param_name in sql_params:
sql = sql.replace(('{' + '{0}'.format(param_name) + '}'),
sql_params[param_name])
return sql |
def squash_whitespace(text):
"""Squash all single or repeating whitespace characters in `text` to one space character.
>>> squash_whitespace('my name \t\t is \\n zach.')
'my name is zach.'
"""
words = text.split()
return ' '.join(words) |
def add2possible_rinex(possible_rinex_dct, mark_name_dso, remote_fn, local_fn):
""" Update possible_rinex_dct for key=mark_name_dso with the tuple:
(remote_fn, local_fn)
"""
if mark_name_dso not in possible_rinex_dct:
possible_rinex_dct[mark_name_dso] = [(remote_fn, local_fn)]
else:
possible_rinex_dct[mark_name_dso].append((remote_fn, local_fn))
return possible_rinex_dct |
def inherits_from(obj, parent):
"""
Takes an object and tries to determine if it inherits at *any*
distance from parent.
Args:
obj (any): Object to analyze. This may be either an instance
or a class.
parent (any): Can be either instance, class or python path to class.
Returns:
inherits_from (bool): If `parent` is a parent to `obj` or not.
Notes:
What differs this function from e.g. `isinstance()` is that `obj`
may be both an instance and a class, and parent may be an
instance, a class, or the python path to a class (counting from
the evennia root directory).
"""
if callable(obj):
# this is a class
obj_paths = ["%s.%s" % (mod.__module__, mod.__name__) for mod in obj.mro()]
else:
obj_paths = ["%s.%s" % (mod.__module__, mod.__name__) for mod in obj.__class__.mro()]
if isinstance(parent, str):
# a given string path, for direct matching
parent_path = parent
elif callable(parent):
# this is a class
parent_path = "%s.%s" % (parent.__module__, parent.__name__)
else:
parent_path = "%s.%s" % (parent.__class__.__module__, parent.__class__.__name__)
return any(1 for obj_path in obj_paths if obj_path == parent_path) |
def minAddToMakeValid(S):
"""
Idea 1:
- count up number of '(' chars
- do the same for ')'
- return the difference
O(n) - time, O(1) space
Idea #2 - expected indices
- init count of min_needed = 0
- iterate over the string
- if '(' and count cuurently 0:
- count up number of repeated '('
- increment
- elif ')' and count > 1:
- count up number of repeated ')'
- decrease the count by that amount
- elif ')' and count == 0:
- count up repeated ')'
- increase by that amount
"""
# count of minimum needed
min_needed = 0
# iterate over the string
index = 0
# useful constant
STR_LENGTH = len(S)
while index < STR_LENGTH:
character = S[index]
# increase min_needed by repeated characters
if character == "(" or (character == ")" and min_needed == 0):
count_char = 0
# find number of repeated chars
while index < STR_LENGTH and S[index] == character:
index += 1
count_char += 1
# increase by that amount
min_needed += count_char
else:
# otherwise decrease the min_needed
while min_needed > 0 and S[index] == ")":
min_needed -= 1
index += 1
return min_needed |
def _upper(val):
"""
Returns *val*, uppercased.
>>> _upper('a')
'A'
"""
return val.upper() |
def str_to_utf8(x):
""" #Before writing/output to printer put in utf-8 """
try:
return x.encode("utf-8")
except:
return x |
def _DamerauLevenshtein(a, b):
"""Damerau-Levenshtein edit distance from a to b."""
memo = {}
def Distance(x, y):
"""Recursively defined string distance with memoization."""
if (x, y) in memo:
return memo[x, y]
if not x:
d = len(y)
elif not y:
d = len(x)
else:
d = min(
Distance(x[1:], y) + 1, # correct an insertion error
Distance(x, y[1:]) + 1, # correct a deletion error
Distance(x[1:], y[1:]) + (x[0] != y[0])) # correct a wrong character
if len(x) >= 2 and len(y) >= 2 and x[0] == y[1] and x[1] == y[0]:
# Correct a transposition.
t = Distance(x[2:], y[2:]) + 1
if d > t:
d = t
memo[x, y] = d
return d
return Distance(a, b) |
def apply_ema(y, alpha=0.99):
"""
EMA for an 1D array
:param y:
:return:
"""
st = y[0]
y_ = [y[0]]
for i in range(1, len(y)):
st = alpha * st + (1 - alpha) * y[i]
y_.append(st)
return y_ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.