content stringlengths 42 6.51k |
|---|
def normalize_enum_constant(s):
"""Return enum constant `s` converted to a canonical snake-case."""
if s.islower(): return s
if s.isupper(): return s.lower()
return "".join(ch if ch.islower() else "_" + ch.lower() for ch in s).strip("_") |
def combine(list_of_values, sep=','):
"""Split and sum list of sep string into one list.
"""
combined = sum(
[str(values).split(sep) for values in list(list_of_values)],
[]
)
if combined == ['-']:
combined = None
return combined |
def pa_bbm_hash_mock(url, request):
"""
Mock for Android autoloader lookup, new site.
"""
thebody = "http://54.247.87.13/softwareupgrade/BBM/bbry_qc8953_autoloader_user-common-AAL093.sha512sum"
return {'status_code': 200, 'content': thebody} |
def index2slot(sx, sy, ox, oy):
"""**Return slot number of an inventory correlating to a 2d index**."""
print((sx, sy, ox, oy))
if not (0 <= sx < ox and 0 <= sy < oy):
raise ValueError(f"{sx, sy} is not within (0, 0) and {ox, oy}!")
return sx + sy * ox |
def _to_camel_case(string):
"""Switch from snake to camelcase strict.
Note:
This currently capitalizes the first word which is not correct
camelcase.
"""
return string.replace('_', ' ').title().replace(' ', '') |
def dump_cookies(cookies_list):
"""Dumps cookies to list
"""
cookies = []
for c in cookies_list:
cookies.append({
'name': c.name,
'domain': c.domain,
'value': c.value})
return cookies |
def generate_base_code(naval_base: bool,
scout_base: bool,
pirate_base: bool) -> str:
"""Returns a base code, one of:
A -- Naval Base and Scout Base/Outpost
G -- Scout Base/Outpost and Pirate Base
N -- Naval Base
P -- Pirate Base
S -- Scout Base/Outpost
"""
if naval_base and scout_base:
return "A"
elif scout_base and pirate_base:
return "G"
elif naval_base:
return "N"
elif pirate_base:
return "P"
elif scout_base:
return "S"
else:
return " " |
def c_to_f(c):
"""
Convert celcius to fahrenheit
"""
return c * 1.8 + 32.0 |
def xyz_to_rgb(cs, xc, yc, zc):
"""
Given an additive tricolour system CS, defined by the CIE x
and y chromaticities of its three primaries (z is derived
trivially as 1-(x+y)), and a desired chromaticity (XC, YC,
ZC) in CIE space, determine the contribution of each
primary in a linear combination which sums to the desired
chromaticity. If the requested chromaticity falls outside
the Maxwell triangle (colour gamut) formed by the three
primaries, one of the r, g, or b weights will be negative.
Caller can use constrain_rgb() to desaturate an
outside-gamut colour to the closest representation within
the available gamut and/or norm_rgb to normalise the RGB
components so the largest nonzero component has value 1.
"""
xr = cs["xRed"]
yr = cs["yRed"]
zr = 1 - (xr + yr)
xg = cs["xGreen"]
yg = cs["yGreen"]
zg = 1 - (xg + yg)
xb = cs["xBlue"]
yb = cs["yBlue"]
zb = 1 - (xb + yb)
xw = cs["xWhite"]
yw = cs["yWhite"]
zw = 1 - (xw + yw)
rx = (yg * zb) - (yb * zg)
ry = (xb * zg) - (xg * zb)
rz = (xg * yb) - (xb * yg)
gx = (yb * zr) - (yr * zb)
gy = (xr * zb) - (xb * zr)
gz = (xb * yr) - (xr * yb)
bx = (yr * zg) - (yg * zr)
by = (xg * zr) - (xr * zg)
bz = (xr * yg) - (xg * yr)
rw = ((rx * xw) + (ry * yw) + (rz * zw)) / yw
gw = ((gx * xw) + (gy * yw) + (gz * zw)) / yw
bw = ((bx * xw) + (by * yw) + (bz * zw)) / yw
rx = rx / rw; ry = ry / rw; rz = rz / rw
gx = gx / gw; gy = gy / gw; gz = gz / gw
bx = bx / bw; by = by / bw; bz = bz / bw
r = (rx * xc) + (ry * yc) + (rz * zc)
g = (gx * xc) + (gy * yc) + (gz * zc)
b = (bx * xc) + (by * yc) + (bz * zc)
return(r,g,b) |
def get_pod_unique_name(pod):
"""Returns a unique name for the pod.
It returns a pod unique name for the pod composed of its name and the
namespace it is running on.
:returns: String with namespace/name of the pod
"""
return "%(namespace)s/%(name)s" % pod['metadata'] |
def _octet_bits(o):
"""
Get the bits of an octet.
:param o: The octets.
:return: The bits as a list in LSB-to-MSB order.
:rtype: list
"""
if not isinstance(o, int):
raise TypeError("o should be an int")
if not (0 <= o <= 255):
raise ValueError("o should be between 0 and 255 inclusive")
bits = [0] * 8
for i in range(8):
if 1 == o & 1:
bits[i] = 1
o = o >> 1
return bits |
def average_even_is_average_odd(hand):
"""
:param hand: list - cards in hand.
:return: bool - are even and odd averages equal?
"""
even = 0
odd = 0
even_count = 0
odd_count = 0
for index, element in enumerate(hand):
if index % 2 == 0:
even += element
even_count +=1
else:
odd += element
odd_count += 1
even_avg = even / even_count
odd_avg = odd / odd_count
return even_avg == odd_avg |
def css_dict(style):
"""
Returns a dict from a style attribute value.
Usage::
>>> css_dict('width: 2.2857142857142856%; overflow: hidden;')
{'overflow': 'hidden', 'width': '2.2857142857142856%'}
>>> css_dict('width:2.2857142857142856%;overflow:hidden')
{'overflow': 'hidden', 'width': '2.2857142857142856%'}
"""
if not style:
return {}
try:
return dict([(k.strip(), v.strip()) for k, v in
[prop.split(':') for prop in
style.rstrip(';').split(';')]])
except ValueError as e:
raise ValueError('Could not parse CSS: %s (%s)' % (style, e)) |
def billing_mode_validator(x):
"""
Property: Table.BillingMode
"""
valid_modes = ["PROVISIONED", "PAY_PER_REQUEST"]
if x not in valid_modes:
raise ValueError(
"Table billing mode must be one of: %s" % ", ".join(valid_modes)
)
return x |
def format_size(size):
"""Return file size as string from byte size."""
for unit in ('B', 'KB', 'MB', 'GB', 'TB'):
if size < 2048:
return "%.f %s" % (size, unit)
size /= 1024.0 |
def latex_bold(text: str) -> str:
"""Format text in bold font using Latex."""
return rf"\textbf{{{text}}}" |
def get_right_index_of_name(clean_tree_str, one_name):
"""Get the right index of givin name.
# 111111111122222222
# 0123456789012345678901234567
# |
>>> get_right_index_of_name('((a,((b,c),(ddd,e))),(f,g));', 'ddd')
15
"""
left_index_of_name = clean_tree_str.find(one_name)
while clean_tree_str[left_index_of_name] not in set([',', ';', ')', '"',
"'", '#', '$', '@',
'>', '<']):
left_index_of_name += 1
return left_index_of_name |
def _get_hostname(server):
"""Get server hostname from an atest dict.
>>> server = {'hostname': 'foo.example.com'} # from atest
>>> _get_hostname(server)
'foo'
"""
return server['hostname'].partition('.')[0] |
def indent_string(string: str) -> str:
"""Indents string for printing.
Parameters
----------
string : str
Input string to be printed.
Returns
-------
str
A string representation of lines with indentation.
"""
output = ""
for line in string.splitlines():
output += (" {0}\n".format(line))
return output |
def unravel_group_params(unfolded_parameters_group):
"""Take a dict('group:k'-> p) and return a dict(group -> {k->p})
"""
parameters_group = {}
for k, p in unfolded_parameters_group.items():
group_name, k = k.split(':')
group_params = parameters_group.get(group_name, {})
group_params[k] = p
parameters_group[group_name] = group_params
return parameters_group |
def permutations(input_list):
"""Return a list containing all permutations of the input list.
Note: This is a recursive function.
>>> perms = permutations(['a', 'b', 'c'])
>>> perms.sort()
>>> for perm in perms:
... print perm
['a', 'b', 'c']
['a', 'c', 'b']
['b', 'a', 'c']
['b', 'c', 'a']
['c', 'a', 'b']
['c', 'b', 'a']
"""
out_lists = []
if len(input_list) > 1:
# Extract first item in list.
item = input_list[0]
# Find all permutations of remainder of list. (Recursive call.)
sub_lists = permutations(input_list[1:])
# For every permutation of the sub list...
for sub_list in sub_lists:
# Insert the extracted first item at every position of the list.
for i in range(len(input_list)):
new_list = sub_list[:]
new_list.insert(i, item)
out_lists.append(new_list)
else:
# Termination condition: only one item in input list.
out_lists = [input_list]
return out_lists |
def as_tuple(*values):
"""
Convert sequence of values in one big tuple.
Parameters
----------
*values
Values that needs to be combined in one big tuple.
Returns
-------
tuple
All input values combined in one tuple
Examples
--------
>>> as_tuple(None, (1, 2, 3), None)
(None, 1, 2, 3, None)
>>>
>>> as_tuple((1, 2, 3), (4, 5, 6))
(1, 2, 3, 4, 5, 6)
"""
cleaned_values = []
for value in values:
if isinstance(value, tuple):
cleaned_values.extend(value)
else:
cleaned_values.append(value)
return tuple(cleaned_values) |
def dump_datetime(datetime_obj):
"""convert datetime object to string format"""
if datetime_obj is None:
return None
return datetime_obj.strftime("%Y-%m-%dT%H:%M:%SZ") |
def fib(n):
"""Fibonacci example function
Args:
n (int): integer
Returns:
int: n-th Fibonacci number
"""
assert n > 0
a, b = 1, 1
for _i in range(n - 1):
a, b = b, a + b
return a |
def return_both_present(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs):
return result
if yi >= len(ys):
return result
if xs[xi] < ys[yi]:
xi += 1
elif xs[xi] > ys[yi]:
yi += 1
else:
result.append(xs[xi])
xi += 1
yi += 1 |
def get_vars(theme):
""" Return dict of theme vars. """
return {k: theme[k] for k in iter(theme)} |
def price_text(price):
"""Give price text to be rendered in HTML"""
if price == 0:
return "Gratis"
return str(price) |
def to_string(obj, digits=0):
"""Gets a list or dictionary and converts to a readable string"""
if isinstance(obj, dict):
return [''.join([str(k), ": ", ("{0:0.%df}" % digits).format(v)]) for k, v in obj.items()]
return [("{0:0.%df}" % digits).format(i) for i in obj] |
def make_placeholder(s):
"""Converts a string to placeholder format {{string}}"""
return '{{'+s+'}}' |
def scale2D(v,scale):
"""Returns a scaled 2D vector"""
return (v[0] * scale, v[1] * scale) |
def get_unique_combinations(combinations_per_row):
"""Performs set.union on a list of sets
Parameters
----------
combinations_per_row : List[Set[Tuple[int]]]
list of combination assignments per row
Returns
-------
Set[Tuple[int]]
all unique label combinations
"""
return set.union(*combinations_per_row) |
def _indent(content):
"""Add indentation to all lines except the first."""
lines = content.split("\n")
return "\n".join([lines[0]] + [" " + l for l in lines[1:]]) |
def adjacency_from_edges(edges):
"""Construct an adjacency dictionary from a set of edges.
Parameters
----------
edges : list
A list of index pairs.
Returns
-------
dict
A dictionary mapping each index in the list of index pairs
to a list of adjacent indices.
Examples
--------
.. code-block:: python
#
"""
adj = {}
for i, j in iter(edges):
adj.setdefault(i, []).append(j)
adj.setdefault(j, []).append(i)
return adj |
def derive_single_object_url_pattern(slug_url_kwarg, path, action):
"""
Utility function called by class methods for single object views
"""
if slug_url_kwarg:
return r'^%s/%s/(?P<%s>[^/]+)/$' % (path, action, slug_url_kwarg)
else:
return r'^%s/%s/(?P<pk>\d+)/$' % (path, action) |
def extractDidParts(did):
"""
Parses and returns a tuple containing the prefix method and key string contained in the supplied did string.
If the supplied string does not fit the pattern pre:method:keystr a ValueError is raised.
:param did: W3C DID string
:return: (pre, method, key string) a tuple containing the did parts.
"""
try: # correct did format pre:method:keystr
pre, meth, keystr = did.split(":")
except ValueError as ex:
raise ValueError("Malformed DID value")
if not pre or not meth or not keystr: # check for empty values
raise ValueError("Malformed DID value")
return pre, meth, keystr |
def resource_record(record):
"""
"""
alias_target_dns_name = ''
alias_target_evaluate_health = ''
if record.get("AliasTarget"):
alias_target_dns_name = record.get("AliasTarget")['DNSName'] or None
alias_target_evaluate_health = str(record.get("AliasTarget")['EvaluateTargetHealth']) or None
resource_records = ''
if record.get("ResourceRecords"):
resource_records = "|".join([i["Value"] for i in record.get("ResourceRecords") if i])
r53_type = ''
if record.get("Weight") is not None:
r53_type = 'weighted'
elif record.get("Failover")is not None:
r53_type = 'failover'
elif record.get("SetIdentifier") is not None:
r53_type = 'latency'
else:
r53_type = 'simple'
return {
"name": record.get("Name") or '',
"type": record.get("Type") or '',
"ttl": record.get("TTL"),
"alias_target_dns_name": alias_target_dns_name,
"alias_target_evaluate_health": alias_target_evaluate_health,
"resource_records": resource_records,
"region": record.get("Region"),
"failover": record.get("Failover") or '',
"multivalueanswer": record.get("MultiValueAnswer") or '',
"healthcheck_id": record.get("HealthCheckId") or '',
"traffic_policy_instance_id": record.get("TrafficPolicyInstanceId") or '',
"weight": record.get("Weight") or '',
"set_identifier": record.get("SetIdentifier") or '',
"r53_type": r53_type
} |
def normalized_total_time(p, max_time=86400000): # by default 24 h (in ms)
"""If time was longer than max_time, then return max_time, otherwise return time."""
v = int(p["result.totalTimeSystem"])
return max_time if v > max_time else v |
def does_need_adjust(change, next_value, limit):
"""Check if change of the next_value will need adjust."""
return change and (next_value - 1 < 0 or next_value + 1 >= limit) |
def float_to_decimal(f: float):
"""
This function is necessary because python transform float like
2.0 in '2.00'
"""
return "{:.2f}".format(f) |
def glonass_nav_decode(dwrds: list) -> dict:
"""
Helper function to decode RXM-SFRBX dwrds for GLONASS navigation data.
:param list dwrds: array of navigation data dwrds
:return: dict of navdata attributes
:rtype: dict
"""
return {"dwrds": dwrds} |
def divisible(num):
"""Divisible by 100 is True, otherwise return False."""
return num % 100 == 0 |
def configget(config, section, var, default):
"""
gets parameter from config file and returns a default value
if the parameter is not found
"""
try:
ret = config.get(section, var)
except:
print("returning default (" + default + ") for " + section + ":" + var)
ret = default
return ret |
def userpar_override(pname, args, upars):
"""
Implement user parameter overrides. In this implementation, user
parameters *always* take precedence. Any user parameters passed to the
Primitive class constructor, usually via -p on the 'reduce' command
line, *must* override any specified recipe parameters.
Note: user parameters may be primitive-specific, i.e. passed as
-p makeFringeFrame:reject_method='jilt'
in which case, the parameter will only be overridden for that primitive.
Other primitives with the same parameter (e.g. stackFlats reject_method)
will not be affected.
This returns a dict of the overridden parameters and their values.
"""
parset = {}
for key, val in list(upars.items()):
if ':' in key:
prim, par = key.split(':')
if prim == pname:
parset.update({par: val})
elif key in args:
parset.update({key: val})
return parset |
def parse_int(str, fallback):
""" Safely parses string to integer.
Args:
str: (str) Strint to be parsed.
fallback: (str) Default value.
Returns:
(int) Parsed value or default value in case of failure.
"""
try:
return int(str)
except (ValueError, TypeError):
return fallback |
def repr_args(args, kwargs):
"""Stringify a set of arguments.
Arguments:
args: tuple of arguments as a function would see it.
kwargs: dictionary of keyword arguments as a function would see it.
Returns:
String as you would write it in a script.
"""
args_s = ("{}, " if kwargs else "{}").format(", ".join(map(repr, args))) if args else "" # noqa
kws = ", ".join(["{}={!r}".format(it[0], it[1]) for it in kwargs.items()])
return str(args_s) + str(kws) |
def replace(filename, replacements):
"""Applies any number of substitutions in the replacements map to the file
referenced by filename. Any modified file is written back, and the
original file overwritten. The number of lines modified is returned.
"""
zero = 0
try:
alpha = open(filename).read()
except IOError:
return zero
hits = 0
for key in replacements.keys():
count = alpha.count(key)
if count>0:
alpha = alpha.replace(key, replacements[key])
hits += count
if hits>0:
try:
omega = open(filename, 'w')
omega.write(alpha)
omega.close()
except IOError:
return zero
return hits
else:
return zero |
def encodeUnicodeToBytes(value, errors="strict"):
"""
Accepts an input "value" of generic type.
If "value" is a string of type sequence of unicode (i.e. in py2 `unicode` or
`future.types.newstr.newstr`, in py3 `str`), then it is converted to
a sequence of bytes.
This function is useful for encoding output data when using the
"unicode sandwich" approach, which involves converting unicode (i.e. strings
of type sequence of unicode codepoints) to bytes (i.e. strings of type
sequence of bytes, in py2 `str` or `future.types.newbytes.newbytes`,
in py3 `bytes`) as late as possible when passing a string to a third-party
function that only accepts bytes as input (pycurl's curl.setop is an
example).
py2:
- "errors" can be: "strict", "ignore", "replace", "xmlcharrefreplace"
- ref: https://docs.python.org/2/howto/unicode.html#the-unicode-type
py3:
- "errors" can be: "strict", "ignore", "replace", "backslashreplace",
"xmlcharrefreplace", "namereplace"
- ref: https://docs.python.org/3/howto/unicode.html#the-string-type
"""
if isinstance(value, str):
return value.encode("utf-8", errors)
return value |
def stripped_lines(lines, ignore_comments, ignore_docstrings, ignore_imports):
"""return lines with leading/trailing whitespace and any ignored code
features removed
"""
strippedlines = []
docstring = None
for line in lines:
line = line.strip()
if ignore_docstrings:
if not docstring and \
(line.startswith('"""') or line.startswith("'''")):
docstring = line[:3]
line = line[3:]
if docstring:
if line.endswith(docstring):
docstring = None
line = ''
if ignore_imports:
if line.startswith("import ") or line.startswith("from "):
line = ''
if ignore_comments:
# XXX should use regex in checkers/format to avoid cutting
# at a "#" in a string
line = line.split('#', 1)[0].strip()
strippedlines.append(line)
return strippedlines |
def pprint_lon_lat(lon, lat, decimals=0):
"""Pretty print a lat and and lon
Examples:
>>> pprint_lon_lat(-104.52, 31.123)
'N31W105'
>>> pprint_lon_lat(-104.52, 31.123, decimals=1)
'N31.1W104.5'
"""
# Note: strings must be formatted twice:
# ff = f"{{:02.1f}}" ; f"{hemi_ew}{ff}".format(32.123)
# 'E32.1
hemi_ns = "N" if lat >= 0 else "S"
format_lat = "{:02." + str(decimals) + "f}"
lat_str = f"{hemi_ns}{format_lat}".format(abs(lat))
hemi_ew = "E" if lon >= 0 else "W"
format_lon = "{:03." + str(decimals) + "f}"
lon_str = f"{hemi_ew}{format_lon}".format(abs(lon))
return f"{lat_str}{lon_str}" |
def _get_avoid_options(avoid_boxes):
"""
Extracts checked boxes in Advanced avoid parameters.
:param avoid_boxes: all checkboxes in advanced parameter dialog.
:type avoid_boxes: list of QCheckBox
:returns: avoid_features parameter
:rtype: JSON dump, i.e. str
"""
avoid_features = []
for box in avoid_boxes:
if box.isChecked():
avoid_features.append((box.text()))
return avoid_features |
def default_scrubber (text):
"""
remove spurious punctuation (for English)
"""
return text.lower().replace("'", "") |
def difference(a, b):
"""
Returns the symmetric difference of sets 'a' and 'b'.
In plain english:
Removes all items that occur in both 'a' and 'b'
Difference is actually set_a.symmetric_difference(set_b), not
set.difference(). See 'minus' for set.difference().
"""
return a.symmetric_difference(b) |
def get_angle_from_rotated_rect(rotrect):
"""
Computes the relative angle to the sub needed to align
to the rectangle along its long axis.
"""
# True if taller than wide
if rotrect[1][0] < rotrect[1][1]:
return rotrect[2]
return rotrect[2] + 90 |
def rf_on_val(n):
"""Returns RF 'ON' value for bunchers, DTL or CCL rf,
n can be a string e.g. 'TA' or '05', or a number 5.
Arguments:
n(str or int): module or buncher number
"""
# Make two character area from input
area = str(n).upper().zfill(2)
if area in ['PB', 'MB', 'TA', 'TB', 'TD']:
## ON => RF Drive is ON
## previously: rf_val = 'ON', but now all numeric
# 0 => RF Drive is ON
rf_val = 0
else:
## ON => RF Delay is NO
## previously: rf_val = 'ON', but now all numeric
# 0 => RF is IN-TIME
rf_val = 0
return rf_val |
def get_last_digits_of_bignum(base:int, power:int, digitcount:int) -> str:
"""
Pessimized algorithm for getting the last digits of a bignum.
:param base: base of exponent.
:param power: power of exponent.
:param digitcount: how many digits to return.
:return: str containing the last digits.
"""
n = 1
for i in range(power):
n = n * base
n = str(n)
return n[-digitcount:] |
def make_iterable(obj):
"""Get a iterable obj."""
if isinstance(obj, (tuple, list)):
return obj
return obj, |
def is_prime(number):
"""States if a number is prime.
:param number: A number
:type number: int
:rtype: bool
**Examples**
>>> is_prime(31)
True
>>> is_prime(42)
False
"""
for factor in range(2, number):
if not number % factor:
return False
return True |
def proj4_dict_to_str(proj4_dict, sort=False):
"""Convert a dictionary of PROJ.4 parameters to a valid PROJ.4 string"""
items = proj4_dict.items()
if sort:
items = sorted(items)
params = []
for key, val in items:
key = str(key) if key.startswith('+') else '+' + str(key)
if key in ['+no_defs', '+no_off', '+no_rot']:
param = key
else:
param = '{}={}'.format(key, val)
params.append(param)
return ' '.join(params) |
def time2float(line):
""" converts formatted time 'nn:nn:nn:nnnnn' to float
>>> time2float('21:33:25:5342')
77605.005342000004
"""
spline = line.split(':')
ints = [int(spline[i]) for i in range(4)]
result = 3600*ints[0] + 60*ints[1] + ints[2] + 1E-6*ints[3]
return result |
def arrow_out(value):
"""Convert an Arrow object to timestamp.
:param Arrow value: The Arrow time or ``None``.
:returns int: The timestamp, or ``None`` if the input is ``None``.
"""
return value.timestamp if value else None |
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters
----------
x : int
n : int
Minimum number of digits. If x needs less digits in binary, the rest
is filled with zeros.
Returns
-------
str
"""
return format(x, 'b').zfill(n) |
def findKeyInJson(jsonDict, searchKey):
""" Search for recursive for a key in a JSON dictionary.
General purpose function to look for a key in a json file.
Parameters
----------
jsonDict : dict()
Dictionary containing a json structure
searchKey : str
The key to look for in the settings
Returns
-------
value : jsonObject
The json object that is found behind the searchKey.
"""
for key in jsonDict:
value = jsonDict[key]
if key == searchKey:
return value
elif isinstance(value, dict):
#launch recursion
inner = findKeyInJson(value, searchKey)
if inner is not None:
return inner
return None |
def kelvin_to_rankine(temp):
"""
From Kelvin (K) to Rankine (R)
"""
return temp*9/5 |
def hex2rgb(str_rgb):
"""Transform hex RGB representation to RGB tuple.
:param str_rgb: 3 hex char or 6 hex char string representation
:returns: RGB 3-uple of float between 0 and 1
>>> from ase_notebook.color import hex2rgb
>>> hex2rgb('#00ff00')
(0.0, 1.0, 0.0)
>>> hex2rgb('#0f0')
(0.0, 1.0, 0.0)
>>> hex2rgb('#aaa') # doctest: +ELLIPSIS
(0.66..., 0.66..., 0.66...)
>>> hex2rgb('#aa') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Invalid value '#aa' provided for rgb color.
"""
try:
rgb = str_rgb[1:]
if len(rgb) == 6:
r, g, b = rgb[0:2], rgb[2:4], rgb[4:6]
elif len(rgb) == 3:
r, g, b = rgb[0] * 2, rgb[1] * 2, rgb[2] * 2
else:
raise ValueError()
except Exception:
raise ValueError("Invalid value %r provided for rgb color." % str_rgb)
return tuple(float(int(v, 16)) / 255 for v in (r, g, b)) |
def dump_required_field(value):
"""dump required_field"""
if value is True:
return "y"
return "n" |
def check_views(views):
"""Checks which views were selected."""
if views is None:
return range(3)
views = [int(vw) for vw in views]
out_views = list()
for vw in views:
if vw < 0 or vw > 2:
print('one of the selected views is out of range - skipping it.')
out_views.append(vw)
if len(out_views) < 1:
raise ValueError(
'Atleast one valid view must be selected. Choose one or more of 0, 1, 2.')
return out_views |
def is_dataclass(value):
"""
Dataclass support is only enabled in Python 3.7+, or in 3.6 with the `dataclasses` backport installed
"""
try:
from dataclasses import is_dataclass
return is_dataclass(value)
except ImportError:
return False |
def validate_rsvps(args):
"""validate rsvp details"""
try:
if args["response"] == '' or \
args["user_id"] == '' or \
args["meetup_id"] == '':
return{
"status": 401,
"error": "Fields cannot be left empty"
}, 401
elif (args["response"]. isdigit()):
return{
"status": 401,
"error": "The fields should be described in words"
}, 401
elif(args["meetup_id"]. isalpha()) or (args["user_id"]. isalpha()):
return{
"status": 401,
"error": "The fields requiring id should be integers"
}, 401
elif (args["response"] != "yes"):
return{
"status": 401,
"error": "The response should either be yes, no or maybe..."
}, 401
else:
return "valid"
except Exception as error:
return{
"status": 401,
"error": "please provide all the fields, missing " + str(error)
}, 401 |
def reverse(str):
"""Reverses the characters in a string."""
return str[::-1] |
def statement_passive_verb(stmt_type):
"""Return the passive / state verb form of a statement type.
Parameters
----------
stmt_type : str
The lower case string form of a statement type, for instance,
'phosphorylation'.
Returns
-------
str
The passive/state verb form of a statement type, for instance,
'phosphorylated'.
"""
override = {
'complex': 'bound',
'regulateamount': 'amount regulated',
'decreaseamount': 'decreased',
'increaseamount': 'increased',
'gap': 'GAP-regulated',
'gef': 'GEF-regulated',
'gtpactivation': 'GTP-activated',
'influence': 'influenced',
'event': 'happened',
'conversion': 'converted',
'modification': 'modified',
'addmodification': 'modified',
'removemodification': 'unmodified',
'regulateactivity': 'activity regulated',
}
return override.get(stmt_type) if stmt_type in override else \
stmt_type[:-3] + 'ed' |
def _parse_file_move(file_move):
"""Return the (old_filename, new_filename) tuple for a file move."""
_, old_filename, new_filename = file_move.split()
return (old_filename, new_filename) |
def try_read_file(path, length):
"""Try to read the designated file with the specified length. Fill with
zeroes if it does not exist."""
try:
with open(path, "rb") as f:
bytes = f.read()
# If the file was as long as expected, return its contents
if len(bytes) == length:
return bytes
except FileNotFoundError:
pass
# Otherwise return zeroes
return bytearray(length) |
def cell_background_number_of_cases(val,max):
"""Creates the CSS code for a cell with a certain value to create a heatmap effect
Args:
val ([int]): the value of the cell
Returns:
[string]: the css code for the cell
"""
opacity = 0
try:
v = abs(val)
color = '193, 57, 43'
value_table = [ [0,0],
[0.00390625,0.0625],
[0.0078125, 0.125],
[0.015625,0.25],
[0.03125,0.375],
[0.0625,0.50],
[0.125,0.625],
[0.25,0.75],
[0.50,0.875],
[0.75,0.9375],
[1,1]]
for vt in value_table:
#print (f"{v} - {vt[0]}")
if v >= round(vt[0]*max) :
opacity = vt[1]
#print (f"{v} - {vt[0]} YES")
except:
# give cells with eg. text or dates a white background
color = '255,255,255'
opacity = 1
return f'background: rgba({color}, {opacity})' |
def _MakeCounterName(key_id, tag):
"""Helper to create a sharded Counter name.
Args:
key_id: Int unique id (usually a model entity id).
tag: String tag which hints at the counter purpose.
Returns:
String to be used as a sharded Counter name.
"""
return '%s_%s' % (key_id, tag) |
def format_usgs_sw_site_id(stationID):
"""Add leading zeros to NWIS surface water sites, if they are missing.
See https://help.waterdata.usgs.gov/faq/sites/do-station-numbers-have-any-particular-meaning.
Zeros are only added to numeric site numbers less than 15 characters in length.
"""
if not str(stationID).startswith('0') and str(stationID).isdigit() and \
0 < int(str(stationID)[0]) < 10 and len(str(stationID)) < 15:
return '0{}'.format(stationID)
return str(stationID) |
def format_sort_key(sort_key):
"""
format sort key (list of integers) with | level boundaries
>>> str(format_sort_key([1, 0, 65535]))
'0001 | FFFF'
"""
return " ".join(
("{:04X}".format(x) if x else "|") for x in sort_key
) |
def calcFixedAspectRatio(win_dim, tar_dim):
"""
@param: win_dim current window dim (width, height)
@param: tar_dim target image dim (width, height)
"""
w, h = win_dim
tw, th = tar_dim
if w > h:
h_r = h ; w_r = int(h * (tw/ th))
if w_r > w:
h_r = int(w * (th / tw))
w_r = w
else: # h > w:
w_r = w ; h_r = int(w * (th / tw))
if h_r > h:
h_r = h
w_r = int(h * (tw / th))
sz = (w_r, h_r)
if 0 in sz:
return 0, sz, 0, 0, 0, 0
else:
sx = (w >> 1) - ((w_r + 1) >> 1) ; ex = sx + w_r
sy = (h >> 1) - ((h_r + 1) >> 1) ; ey = sy + h_r
if sx < 0: ex -= sx ; sx = 0
if sy < 0: ey -= sy ; sy = 0
if ex > w: sx -= w - ex ; ex = w
if ey > h: sy -= h - ey ; ey = h
return 1, sz, sx, sy, ex, ey |
def s_to_min(value):
"""Convert seconds to minutes."""
return "{}:{:02d}".format(int(value // 60), int(value % 60)) |
def split_dict(dic, *keys):
"""Return two copies of the dict. The first will contain only the
specified items. The second will contain all the *other* items from the
original dict.
Example::
>>> split_dict({"From": "F", "To": "T", "Received", R"}, "To", "From")
({"From": "F", "To": "T"}, {"Received": "R"})
"""
for k in keys:
if k not in dic:
raise KeyError("key {!r} is not in original mapping".format(k))
r1 = {}
r2 = {}
for k, v in dic.items():
if k in keys:
r1[k] = v
else:
r2[k] = v
return r1, r2 |
def fill_width(bytes_, width):
"""
Ensure a byte string representing a positive integer is a specific width
(in bytes)
:param bytes_:
The integer byte string
:param width:
The desired width as an integer
:return:
A byte string of the width specified
"""
while len(bytes_) < width:
bytes_ = b'\x00' + bytes_
return bytes_ |
def __trimTrailingSlash__(args):
"""
Takes in a list filepaths and removes any trailing /'s
:param arg: list of string file paths
:return: list of filepaths with trailing /'s removed
"""
for i in range(len(args)):
if args[i][-1] == "/":
args[i] = args[i][:-1]
return args |
def utf8len(s):
"""
Get the byte number of the utf-8 sentence.
"""
return len(s.encode('utf-8')) |
def is_lambda_map(mod):
"""check for the presence of the LambdaMap block used by the
torch -> pytorch converter
"""
return 'LambdaMap' in mod.__repr__().split('\n')[0] |
def get_tag_type(tag):
""" Simple helper """
return tag.split('-')[-1] |
def demo(name: str, demo: str) -> str:
"""Description."""
return f"{name}: {demo}" |
def int_to_bytes(n, minlen=0): # helper function
""" Int/long to byte string. """
nbits = n.bit_length() + (1 if n < 0 else 0) # plus one for any sign bit
nbytes = (nbits+7) // 8 # number of whole bytes
b = bytearray()
for _ in range(nbytes):
b.append(n & 0xff)
n >>= 8
if minlen and len(b) < minlen: # zero pad?
b.extend([0] * (minlen-len(b)))
return bytearray(reversed(b)) |
def flatten_dict(d, delim="_"):
"""Go from {prefix: {key: value}} to {prefix_key: value}."""
flattened = {}
for k, v in d.items():
if isinstance(v, dict):
for k2, v2 in v.items():
flattened[k + delim + k2] = v2
else:
flattened[k] = v
return flattened |
def extended_gcd(a, b):
"""
>>> extended_gcd(10, 6)
(2, -1, 2)
>>> extended_gcd(7, 5)
(1, -2, 3)
"""
assert a >= 0 and b >= 0
if b == 0:
d, x, y = a, 1, 0
else:
(d, p, q) = extended_gcd(b, a % b)
x = q
y = p - q * (a // b)
assert a % d == 0 and b % d == 0
assert d == a * x + b * y
return (d, x, y) |
def simtelHistogramFileName(run, primary, arrayName, site, zenith, azimuth, label=None):
"""
sim_telarray histogram file name.
Warning
-------
zst extension is hardcoded here.
Parameters
----------
arrayName: str
Array name.
site: str
Paranal or LaPalma.
zenith: float
Zenith angle (deg).
viewCone: list of float
View cone limits (len = 2).
run: int
Run number.
label: str
Instance label.
Returns
-------
str
File name.
"""
name = "run{}_{}_za{:d}deg_azm{:d}deg-{}-{}".format(
run, primary, int(zenith), int(azimuth), site, arrayName
)
name += "_{}".format(label) if label is not None else ""
name += ".hdata.zst"
return name |
def sort_module_names(modlst):
"""
Sort a list of module names in order of subpackage depth.
Parameters
----------
modlst : list
List of module names
Returns
-------
srtlst : list
Sorted list of module names
"""
return sorted(modlst, key=lambda x: x.count('.')) |
def rreplace(s, old, new, occurrence=-1):
"""
Replace old with new starting from end of the string
:param s: The string to be transformed
:param old: Search string
:param new: Replacement string
:param occurrence: Number of replacements to do
:return:
"""
li = s.rsplit(old, occurrence)
return new.join(li) |
def dedup_and_title_case_names(names):
"""Should return a list of title cased names,
each name appears only once"""
# return a list of a dict keys
# by rule the keys of a dict are unique
# list comprehension
# title() capitalize all the words and lowers
# the rest
return list({name.title() for name in names}) |
def nn_min(x: int, y: int) -> int:
"""
the non-negative minimum of x and y
"""
if x < 0:
return y
if y < 0:
return x
if x < y:
return x
return y |
def markup_num(n_str):
"""Generate Wikipedia markup for case numbers in region table."""
return ' style="color:gray;" |0' if n_str == '0' else n_str |
def axiom_generator_percept_sentence(t, tvec):
"""
Asserts that each percept proposition is True or False at time t.
t := time
tvec := a boolean (True/False) vector with entries corresponding to
percept propositions, in this order:
(<stench>,<breeze>,<glitter>,<bump>,<scream>)
Example:
Input: [False, True, False, False, True]
Output: '~Stench0 & Breeze0 & ~Glitter0 & ~Bump0 & Scream0'
"""
"*** YOUR CODE HERE ***"
percept = ["Stench","Breeze","Glitter","Bump","Scream"]
axiom_str = ''
for i in range(len(percept)):
if not tvec[i]:
percept[i] = "~" + percept[i]
percept = [s + str(t) for s in percept]
axiom_str = ' & '.join(percept)
# Comment or delete the next line once this function has been implemented.
#utils.print_not_implemented()
return axiom_str |
def get_config_options(otype):
""" Return list of valid configuration options for nodes and dispatcher."""
if otype is 'node':
return ['node_name', 'node_type', 'node_id', 'node_description', 'primary_node', 'ip', 'port_frontend', 'port_backend', 'port_publisher', 'n_responders', 'lsl_stream_name', 'primary_n_channels', 'primary_channel_names', 'primary_channel_descriptions', 'primary_sampling_rate', 'primary_buffer_size_s', 'run_publisher', 'secondary_node', 'secondary_n_channels', 'secondary_buffer_size', 'secondary_channel_names', 'secondary_channel_descriptions', 'default_channel']
elif otype is 'dispatcher':
return ['node_list', 'port', 'ip', 'n_threads', 'run_pubsub_proxy', 'proxy_port_in', 'proxy_port_out']
else:
return None |
def Or(input1,input2):
"""
Logic for OR operation
Parameters
----------
input1 (Required) : First input value. Should be 0 or 1.
input2 (Required) : Second input value. Should be 0 or 1.
"""
return f"( {input1} | {input2} )" |
def filter_dict_values(D):
"""Return a shallow copy of D with all `None` values excluded.
>>> filter_dict_values({'a': 1, 'b': 2, 'c': None})
{'a': 1, 'b': 2}
>>> filter_dict_values({'a': 1, 'b': 2, 'c': 0})
{'a': 1, 'b': 2, 'c': 0}
>>> filter_dict_values({})
{}
>>> filter_dict_values({'imnone': None})
{}
"""
return {k: v for k, v in D.items() if v is not None} |
def parse_input(puzzle_input: str) -> range:
"""Split the input of dash-separated numbers into an inclusive range"""
start, last = map(int, puzzle_input.split("-"))
return range(start, last + 1) |
def get_rhombus_image (key: str) -> str:
"""Return the full uri of a face image given an aws s3 key
:param key: The key to get the URI for
:return: The full URI of the image
"""
return "https://media.rhombussystems.com/media/faces?s3ObjectKey=" + key |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.