content stringlengths 42 6.51k |
|---|
def calc_eirp(power, antenna_gain):
"""
Calculate the Equivalent Isotropically Radiated Power.
Equivalent Isotropically Radiated Power (EIRP) = (
Power + Gain
)
Parameters
----------
power : float
Transmitter power in watts.
antenna_gain : float
Antenna gain in dB.
losses : float
Antenna losses in dB.
Returns
-------
eirp : float
eirp in dB.
"""
eirp = power + antenna_gain
return eirp |
def priority_split(text, *splitters):
"""When we don't know which character is being used to combine text, run
through a list of potential splitters and split on the first"""
present = [s for s in splitters if s in text]
# fall back to non-present splitter; ensures we have a splitter
splitters = present + list(splitters)
splitter = splitters[0]
return [seg.strip() for seg in text.split(splitter) if seg.strip()] |
def build_abstract(*args):
"""Combines multiple messages into a single abstract over multiple lines.
>>> build_abstract("test1", "test2")
'test1\\ntest2'
"""
return "\n".join([_arg for _arg in args if _arg]) |
def should_include(page, target_name):
"""Report whether a given page should be part of the given target"""
if "targets" not in page:
return False
if target_name in page["targets"]:
return True
else:
return False |
def make_enum(members):
"""All C enums with no specific values follow the pattern 0, 1, 2... in the order they are in source."""
enum = {}
for i, member in enumerate(members):
keys = [member]
if isinstance(member, tuple):
# this member has multiple names!
keys = member
for key in keys:
enum[key] = i
return enum |
def to_human_readable_in_hours(seconds):
"""
* Seconds are not displayed.
* Negative time supported.
In : to_human_readable_in_hours(1)
Out: '0:00'
In : to_human_readable_in_hours(100)
Out: '0:01'
In : to_human_readable_in_hours(213321)
Out: '59:15'
In : to_human_readable_in_hours(-2000)
Out: '-0:33'
"""
sign = ''
if seconds < 0:
sign = '-'
seconds = abs(seconds)
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "%s%d:%02d" % (sign, h, m) |
def _check_schema_file_content_for_reference_to_json(fs):
"""
checks file contents fs for .json
:param fs:
:return: True/False
"""
"""
:param fs:
:return:
"""
seek = u".json"
if fs.find(seek) != -1:
return False
return True |
def bt_sdpclass(sdpclass):
""" Returns a string describing service class """
serviceclasses = {
0x1000 : "SDP Server",
0x1001 : "Browse Group",
0x1002 : "Public Browse Group",
0x1101 : "Serial Port",
0x1102 : "LAN Access",
0x1103 : "Dialup Networking",
0x1104 : "IRMC Sync",
0x1105 : "OBEX Object Push",
0x1106 : "OBEX File Transfer",
0x1107 : "IRMC Sync Command",
0x1108 : "Ultimate Headset",
0x1109 : "Cordless Telephone",
0x110a : "Audio Source",
0x110b : "Audio Sink",
0x110c : "AV Remote Target",
0x110d : "Advanced Audio",
0x110e : "AV Remote",
0x110f : "Video Conferencing",
0x1110 : "Intercom",
0x1111 : "Fax",
0x1112 : "Headset Audio Gateway",
0x1113 : "Wireless Application Protocol",
0x1114 : "Wireless Applicatio Protocol Client",
0x1115 : "Personal Area Networking User",
0x1116 : "Network Application Profile",
0x1117 : "Group Networking",
0x1118 : "Direct Printing",
0x1119 : "Reference Printing",
0x111a : "Imaging",
0x111b : "Imaging Responder",
0x111c : "Imaging Archive",
0x111d : "Imaging Reference Objects",
0x111e : "Handsfree",
0x111f : "Handsfree Audio Gateway",
0x1120 : "Direct Print Reference Objects",
0x1121 : "Reflected UI",
0x1122 : "Basic Printing",
0x1123 : "Printing Status",
0x1124 : "Human Interface Device",
0x1125 : "Handheld Contactless Card Terminal",
0x1126 : "Handheld Contactless Card Terminal Print",
0x1127 : "Handheld Contactless Card Terminal Scanning",
0x1129 : "Video Conferencing Gateway",
0x112a : "Unrestricted Digital Information",
0x112b : "Unrestricted Digital Information",
0x112c : "Audio Visual",
0x112d : "Service Application Profile",
0x112e : "Phone Book Access Profile",
0x112f : "Phone Book Access Profile",
0x1200 : "Plug-and-Play Information",
0x1201 : "Generic Networking",
0x1202 : "Generic File Transfer",
0x1203 : "Generic Audio",
0x1204 : "Generic Telephony",
0x1205 : "Universal Plug-and-Play",
0x1206 : "Universal Plug-and-Play IP",
0x1300 : "Universal Plug-and-Play PAN",
0x1301 : "Universal Plug-and-Play LAP",
0x1302 : "Universal Plug-and-Play L2CAP",
0x1303 : "Video Source",
0x1304 : "Video Sink",
0x1305 : "Video Distribution",
0x2112 : "Apple Agent"
}
try:
return serviceclasses[sdpclass]
except:
return "Unknown (" + str(sdpclass) + ")" |
def test_function(w: float,
s: float,
beta: float,
alpha: float,
p: float,
b: float,
U: float,
q: int,
high_val_consumers_up: float,
L: float,
high_val_consumers_down: float) -> bool:
"""
Summary line.
Extended description of function.
Parameters
----------
w: description
s: description
beta: description
alpha: description
p: description
b: description
U: description
q: description
high_val_consumers_up: description
L: description
high_val_consumers_down: description
Returns
-------
The appropriate integer for that selection.
"""
return (((w * s) + 0.0000000000001) <
(beta * alpha *
(p - max(b,
min(p,
b + (p - b) *
(U - (q - high_val_consumers_up - 1))/(U + 1)))) +
(beta * (1 - alpha) *
(p - max(b,
min(p,
b + (p - b) * (U - (q - high_val_consumers_down - 1))/(U + 1))))) +
((1 - beta) *
(1 - alpha) * (p - max(b,
min(p,
b + (p - b) *
(L - (q - high_val_consumers_down - 1))/(L + 1))))) +
((1 - beta) *
alpha * (p - max(b, min(p,
b + (p - b) *
(L - (q - high_val_consumers_up - 1))/(L + 1))))))) |
def _x_proto_matcher(art):
""" Is this artifact the x.proto file? """
return art['name'].endswith('.proto') |
def isempty(s):
"""
return if input object(string) is empty
"""
if s in (None, "", "-", []):
return True
return False |
def RGB_2_xy(R, G, B):
""" Convert from RGB color to XY color. """
if R + G + B == 0:
return 0, 0
var_R = (R / 255.)
var_G = (G / 255.)
var_B = (B / 255.)
if var_R > 0.04045:
var_R = ((var_R + 0.055) / 1.055) ** 2.4
else:
var_R /= 12.92
if var_G > 0.04045:
var_G = ((var_G + 0.055) / 1.055) ** 2.4
else:
var_G /= 12.92
if var_B > 0.04045:
var_B = ((var_B + 0.055) / 1.055) ** 2.4
else:
var_B /= 12.92
var_R *= 100
var_G *= 100
var_B *= 100
# Observer. = 2 deg, Illuminant = D65
X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805
Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722
Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505
# Convert XYZ to xy, see CIE 1931 color space on wikipedia
return X / (X + Y + Z), Y / (X + Y + Z) |
def list_to_string(list_of_elements):
"""
Converts the given list of elements into a canonical string representation for the whole list.
"""
return '-'.join(map(lambda x: str(x), sorted(list_of_elements))) |
def filter_by_scores(type2freq, type2score, stop_lens):
"""
Loads a dictionary of type scores
Parameters
----------
type2freq: dict
Keys are types, values are frequencies of those types
type2score: dict
Keys are types, values are scores associated with those types
stop_lens: iteratble of 2-tuples
Denotes intervals that should be excluded when calculating shift scores
Returns
-------
type2freq_new,type2score_new: dict,dict
Frequency and score dicts filtered of words whose score fall within stop
window
"""
type2freq_new = dict()
type2score_new = dict()
stop_words = set()
for lower_stop, upper_stop in stop_lens:
for t in type2score:
if (
(type2score[t] < lower_stop) or (type2score[t] > upper_stop)
) and t not in stop_words:
try:
type2freq_new[t] = type2freq[t]
except KeyError:
pass
type2score_new[t] = type2score[t]
else:
stop_words.add(t)
return type2freq_new, type2score_new, stop_words |
def get_color_map_list(num_classes):
""" Returns the color map for visualizing the segmentation mask,
which can support arbitrary number of classes.
Args:
num_classes: Number of classes
Returns:
The color map
"""
color_map = num_classes * [0, 0, 0]
for i in range(0, num_classes):
j = 0
lab = i
while lab:
color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
j += 1
lab >>= 3
return color_map |
def dict_key(dict, arg):
"""Returns the given key from a dictionary, with optional default value."""
arg = arg.split(',')
key, default = arg[:2] if len(arg) == 2 else (arg[0], None)
return dict.get(key, default) |
def selection_sort(a):
"""
Use selection sort algorithm to sort array/list
"""
i, n = 0, len(a)
while i < n - 1:
j, small = i + 1, i
while j < n:
if a[small] > a[j]:
small = j
j += 1
a[i], a[small] = a[small], a[i]
i += 1
return a |
def round_to(value: float, target: float):
"""
Round price to price tick value.
"""
rounded = int(round(value / target)) * target
return rounded |
def format_id(id: str, detail: bool = False, prefix=8) -> str:
"""
Display a record id.
"""
if detail:
return id
else:
return id[:prefix] |
def contains(value, arg):
"""
Test whether a value contains any of a given set of strings.
`arg` should be a comma-separated list of strings.
"""
return any(s in value for s in arg.split(",")) |
def shorten_trace_data_paths(trace_data):
"""
Shorten the paths in trace_data to max 3 components
:param trace_data:
:return:
"""
for i, (direction, _script, method, path, db) in enumerate(trace_data):
path = "/".join(path.rsplit('/')[-3:]) # only keep max last 3 components
trace_data[i] = (direction, _script, method, path, db)
return trace_data |
def get_element_text(element_text_object):
""" get metadata for a given Omeka 'element_texts' object """
text = element_text_object['text']
element_set_name = element_text_object['element_set']['name']
element_name = element_text_object['element']['name']
return text, element_set_name, element_name |
def strip_units(value):
"""
Lazy way to strip units - need much better parsing here to detect units
There must be a library somewhere to do this
"""
# inches to cm
if value.endswith("\""):
v = value.replace("\"","")
return float(v)*0.0254
# ounces to grams
elif value.endswith(" oz."):
v = value.replace(" oz.","")
return float(v)*28.35
# no translation needed
else:
return value |
def v5_add(matrix1, matrix2):
"""Add corresponding numbers in given 2-D matrices.
Writing the list comprehension as a one-liner
"""
combined = []
for row1, row2 in zip(matrix1, matrix2):
combined.append([n + m for n, m in zip(row1, row2)])
return combined |
def _text(text):
""" Returns normal text string """
return f'{text}\n\n' |
def _parse_exception(e):
"""Parses an exception, returns its message."""
# Lazily import
import re
# MySQL
matches = re.search(r"^\(_mysql_exceptions\.OperationalError\) \(\d+, \"(.+)\"\)$", str(e))
if matches:
return matches.group(1)
# PostgreSQL
matches = re.search(r"^\(psycopg2\.OperationalError\) (.+)$", str(e))
if matches:
return matches.group(1)
# SQLite
matches = re.search(r"^\(sqlite3\.OperationalError\) (.+)$", str(e))
if matches:
return matches.group(1)
# Default
return str(e) |
def to_bool(v):
"""Convert boolean-like value of html attribute to python True/False
Example truthy values (for `attr` in <b> ):
<b attr> <b attr="1"> <b attr="true"> <b attr="anything">
example falsy values:
<b attr="0"> <b attr="false"> <b attr="False">
"""
return v is None or (v not in ('0', 'false', 'False')) |
def posstr(pos_list):
"""
Stringify pos list
"""
return ''.join(map(str, pos_list)) |
def indentation(line):
""" returns the number of indents from a line. indents are 4 spaces long """
return (len(line) - len(line.lstrip())) / 4 |
def veh_filter(city_loc="boston-ma",
search_radius=25,
current_page_num=100
):
"""
Function to define a filter to select vehicles.
The default searches all vehicles
within 50 miles of Worcester MA
"""
url = (
"https://www.truecar.com/used-cars-for-sale/listings/"
+ "location-" + city_loc
+ "?page=" + str(current_page_num)
+ "&searchRadius=" + str(search_radius)
+ "&sort[]=distance_asc_script"
)
return url |
def cutlabel(s, cuts):
"""Cuts a string s using a set of (n, label) cuts.
Returns a list of (sub, label) pairs.
If there was an initial part before the first cut, then it has a label of None.
If there are no cuts, returns s as a single element, with label None.
"""
cuts = sorted(cuts)
# no cuts -> whole string is an element
if not cuts: return [(s, None)]
if cuts[0][0] != 0:
cuts.insert(0, (0, None))
if cuts[-1][0] < len(s)-1:
cuts.append((len(s), None))
locs, labels = zip(*cuts)
ret = []
for i, j, label in zip(locs, locs[1:], labels):
ret.append((s[i:j], label))
return ret |
def whereStartEndPairsInRange(startIdxs, endIdxs, minStartIdx, maxEndIdx):
"""Given an ordered collection of start and end pairs, a minimum start
index, and a maximum end index, return the first and last index into the
start and end pairs collection such that the pair at that index is included
in the range (the returned last index is not inclusive, as is typical in
python).
Note that this assumes that both the startIdxs and endIdxs are already
sorted in ascending order. This is necessary for the returned indices
to be meaningful when used to index the arrays passed in.
Returns (-1, -1) if no (start, end) pairs fall in the range
>>> starts = [0, 5]
>>> ends = [1, 10]
>>> minStart, maxEnd = 0, 20
>>> whereStartEndPairsInRange(starts, ends, minStart, maxEnd)
(0, 2)
>>> minStart = 1
>>> whereStartEndPairsInRange(starts, ends, minStart, maxEnd)
(1, 2)
>>> minStart, maxEnd = 0, 8
>>> whereStartEndPairsInRange(starts, ends, minStart, maxEnd)
(0, 1)
>>> minStart, maxEnd = 1, 8
>>> whereStartEndPairsInRange(starts, ends, minStart, maxEnd)
(-1, -1)
"""
# fail fast
assert(len(startIdxs) == len(endIdxs))
empty = (-1, -1)
if not len(startIdxs):
return empty
# find first startIdx >= minStartIdx
tsIdx = -1
ts = -1
while ts < minStartIdx:
try:
tsIdx += 1
ts = startIdxs[tsIdx]
except IndexError: # reached end
break
# find last endIdx < maxEndIdx
teIdx = tsIdx - 1
te = -1
while te < maxEndIdx:
try:
teIdx += 1
te = endIdxs[teIdx]
except IndexError:
break
if tsIdx == teIdx: # empty set
return empty
return tsIdx, teIdx |
def remove_headers(markdown):
"""Remove MAINTAINER and AUTHOR headers from md files."""
for header in ['# AUTHOR', '# MAINTAINER']:
if header in markdown:
markdown = markdown.replace(header, '')
return markdown |
def get_matched_rule(command, rules, settings):
"""Returns first matched rule for command."""
for rule in rules:
if rule.match(command, settings):
return rule |
def _in_order(expected, received):
"""Determine whether or not the received queue is in the order
that we expect. A rule's destination port is used as its ID.
:param expected: list of rules in the expected order.
:param received: list of rules in ACLSwitch's order
:return: True if in order, False otherwise.
"""
list_size = len(expected)
for i in range(list_size):
if str(expected[i]["rule"]["port_dst"]) != str(received[i]):
return False
return True |
def list2str(x: list):
"""
covert all items into strings in an any dimension list.
it's very useful when you want to print an n dimension list while some items in it is pointers.
:param x: (list)
:return: (list of only strings)
"""
_list = []
for _i in x:
if type(_i).__name__ == 'list':
_list.append(list2str(_i))
else:
_list.append(str(_i))
return _list |
def are_collinear(p1, p2, p3, tolerance=0.5):
"""return True if 3 points are collinear.
tolerance value will decide whether lines are collinear; may need
to adjust it based on the XY tolerance value used for feature class"""
x1, y1 = p1[0], p1[1]
x2, y2 = p2[0], p2[1]
x3, y3 = p3[0], p3[1]
res = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)
if -tolerance <= res <= tolerance:
return True |
def rgb_to_hex(rgb):
"""
converts an rgb tuple to a hex string.
>>>rgb_to_hex((255,255,255))
'#FFFFFF'
"""
return '#%X%X%X' % rgb |
def rmRTs(tokens) :
"""Remove RTs"""
return [x for x in tokens if x != "rt"] |
def find_orphaned_ports(all_tenants, port_mappings):
"""port_mappings needs to be a dict of
{'tenant_id': <tenant_id>,
'id': <port_uuid>}"""
orphaned_ports = []
for pair in port_mappings:
if pair['tenant_id'] not in all_tenants:
orphaned_ports.append(pair)
return orphaned_ports |
def _group_consecutives(vals, step=1):
"""Return list of consecutive lists of numbers from vals (number list)."""
run = []
result = [run]
expect = None
for v in vals:
if (v == expect) or (expect is None):
run.append(v)
else:
run = [v]
result.append(run)
expect = v + step
return result |
def parse_component(component):
"""Parse the component coming from the .yaml file.
Args:
component (str or dict): Can be either a str, or a dictionary.
Comes from the .yaml config file. If it is a string,
simply return, since its the component name without arguments.
Otherwise, parse.
Returns:
tuple: tuple containing:
str: name of the method to be called from sound.Waveform
dict: arguments to be unpacked. None if no arguments to
compute.
"""
if isinstance(component, str):
return component, None
elif isinstance(component, dict):
component_name = list(component.keys())[0]
# component[component_name] is a dictionary of arguments.
arguments = component[component_name]
return component_name, arguments
else:
raise ValueError("Argument to the parse_component function must be str or dict.") |
def MRI_color_scheme(lst, color_scheme):
"""
This function converts the MRI images to the specified color
params:
lst - list containing MRI images
color_scheme - string containing the specified color
returns:
lst
"""
lst = [MRI.convert(color_scheme) for MRI in lst]
return lst |
def t2s(x):
"""
Convert 'tanh' encoding to 'sigmoid' encoding
"""
return (x + 1) / 2 |
def make_inv_cts(cts):
"""
cts is e.g. {"Germany" : "DEU"}. inv_cts is the inverse: {"DEU" : "Germany"}
"""
inv_ct = {}
for old_k, old_v in cts.items():
if old_v not in inv_ct.keys():
inv_ct.update({old_v : old_k})
return inv_ct |
def remove_repeats_in_list(list_):
"""Remove repeats in a list.
"""
return list(dict.fromkeys(list_).keys()) |
def _is_valid_color(colors :dict, user_color :str):
"""Returns true if user_color is a graph color provided by matplotlib
Positional Arguments:
colors : dict
- dict of all colors supported by matplotlib passed in
by the graph_colors decorator
user_color : str
- a string representing the name of a color
"""
try:
colors[user_color]
except KeyError:
return False
return True |
def quick_select(values, k, pivot_fn, index=0):
"""
Select the kth element in values (0 based)
:param values: an Iterable object
:param k: Index
:param pivot_fn: Function to choose a pivot, defaults to random.choice
:param index: the position of the iterable to compare
:return: The kth element of values
"""
if len(values) == 1:
assert k == 0
return values[0]
pivot = pivot_fn(values)
lows, highs, equals = [], [], []
for elem in values:
e_value, p_value = elem[index], pivot[index]
if e_value < p_value:
lows.append(elem)
elif e_value > p_value:
highs.append(elem)
else:
equals.append(elem)
if k < len(lows):
return quick_select(lows, k, pivot_fn, index=index)
elif k < len(lows) + len(equals):
# We got lucky and guessed the median
return equals[0]
else:
return quick_select(highs, k - len(lows) - len(equals), pivot_fn, index=index) |
def get_coord_type(coord):
"""
This assumes the given coordinate is indeed a coord type
Args:
coord (str)
Returns:
str ("relative", "local", "absolute"): The coordinate type
"""
coord_dict = {"^": "local", "~": "relative"}
return coord_dict.get(coord[0], "absolute") |
def validateHouse(p_data):
"""Run the range business validation rules.
Validates if a property has the right values for its attributes.
"""
ret = False
if (p_data['beds'] in range(1, 5)) \
and (p_data['baths'] in range(1, 4)) \
and (p_data['squareMeters'] in range(20, 240)) \
and (p_data['long'] in range(0, 1400)) \
and (p_data['lat'] in range(0, 1000)):
ret = True
return ret |
def ts_to_ns(ts):
"""
Convert second timestamp to integer nanosecond timestamp
"""
# XXX Due to limited mantis in float numbers,
# do not multiply directly by 1e9
return int(int(ts * 1e6) * int(1e3)) |
def RETURN_replace_negatives_by_zeros(numbers):
"""
RETURNs a NEW list that is the same as the given list of numbers,
but with each negative number in the list replaced by zero.
For example, if the given list is [-30.2, 50, 12.5, -1, -5, 8, 0].
then the returned list is the NEW list [0, 50, 12.5, 0, 0, 8, 0].
This function must NOT mutate the given list.
Precondition: The argument is a list of numbers.
"""
# DONE: 2. First, READ THE ABOVE TEST CODE.
# Make sure that you understand it.
# Then, IMPLEMENT and test THIS FUNCTION
# (using the above code for testing).
l = []
for i in range(len(numbers)):
if numbers[i] < 0:
l.append(0)
else:
l.append(numbers[i])
return l |
def LM_index(ell, m, ell_min):
"""Array index for given (ell,m) mode
Assuming an array of
[[ell,m] for ell in range(ell_min, ell_max+1)
for m in range(-ell,ell+1)]
this function returns the index of the (ell,m) element. (Note that
ell_max doesn't actually come into this calculation, so it is not taken
as an argument to the function.)
This can be calculated in sympy as
from sympy import symbols, summation
ell,m,ell_min, = symbols('ell,m,ell_min,', integer=True)
summation(2*ell + 1, (ell, ell_min, ell-1)) + (ell+m)
"""
return ell * (ell + 1) - ell_min ** 2 + m |
def config_init(config):
""" Some of the variables that should exist and contain default values """
if "augmentation_mappings_json" not in config:
config["augmentation_mappings_json"] = None
if "augmentation_types_todo" not in config:
config["augmentation_types_todo"] = None
return config |
def check_params_exist(params_list, event, event_attribute=None, is_cfn=False):
"""
Checks that parameters in event exist
Depending on the type of call to the Lambda function,
checks if all the input parameters are present
Args:
----------
params_list: list
List of parameters to check the presence in event
event: dict
Lambda function handler event dict
event_attribute: string
Name of the attribute to check if parameters are
stored within that key of the event dict
is_cfn: bool
Specifies if the caller is CloudFormation and
therefore lookup into ResourceProperties key of event
Returns
------
tuple
0 - bool to inform if the task is successful or failed
1 - string describing which parameter is missing or to say all params have been found
"""
event_lookup = None
if is_cfn and not event_attribute:
event_lookup = "ResourceProperties"
elif not is_cfn and event_attribute:
if not event_attribute in event.keys():
raise AttributeError("Event does not have key {0}".format(event_attribute))
event_lookup = event_attribute
if not event_lookup:
for param in params_list:
if not param in event.keys():
raise AttributeError("{0} not in events attributes".format(param))
else:
print(event_lookup)
print(event[event_lookup])
for param in params_list:
print(param)
if not param in event[event_lookup].keys():
raise AttributeError("{0} not in events attributes".format(param))
return True |
def node_vertex_name(mesh_node, vertex_id):
"""
Returns the full name of the given node vertex
:param mesh_node: str
:param vertex_id: int
:return: str
"""
return '{}.vtx[{}]'.format(mesh_node, vertex_id) |
def all_different(source, image):
"""Check whether source map has fixed point."""
return all([x != y for x, y in zip(source, image)]) |
def force_list(v):
"""
Force single items into a list. This is useful for checkboxes.
"""
if isinstance(v, list):
return v
elif isinstance(v, tuple):
return list(v)
else:
return [v] |
def calc_U_HS(eps, zeta, E, mu):
"""
Helmholtz-Smoluchowski
"""
u_eof = -eps*zeta*E/mu
return u_eof |
def string2number(i):
""" Convert a string to a number
Input: string (big-endian)
Output: long or integer
"""
import codecs
return int(codecs.encode(i, 'hex'), 16) |
def get_empty_instances(active_container_described: dict) -> dict:
"""Returns an object of empty instances in cluster."""
empty_instances = {}
for inst in active_container_described['containerInstances']:
if inst['runningTasksCount'] == 0 and inst['pendingTasksCount'] == 0:
empty_instances.update(
{inst['ec2InstanceId']: inst['containerInstanceArn']}
)
return empty_instances |
def fix_label_lists(tsv_file_lst_lsts):
"""
complex files have first element of complex labels
for an ID
this list is imported as one string and needs to be
list of integers, which is done in this function
output is dict with ID as key and labels as value
labels are ints
"""
comp_dict = {}
for ele in tsv_file_lst_lsts:
comp_dict[ele[1]] = [int(i) for i in ele[0].split(',') ]
return comp_dict |
def merge_bbox(bbox1, bbox2):
"""
Merge two bboxes.
>>> merge_bbox((-10, 20, 0, 30), (30, -20, 90, 10))
(-10, -20, 90, 30)
"""
minx = min(bbox1[0], bbox2[0])
miny = min(bbox1[1], bbox2[1])
maxx = max(bbox1[2], bbox2[2])
maxy = max(bbox1[3], bbox2[3])
return (minx, miny, maxx, maxy) |
def check_do_touch(board_info):
"""."""
do_touch = False
bootloader_file = board_info.get('bootloader.file', '')
if 'caterina' in bootloader_file.lower():
do_touch = True
elif board_info.get('upload.use_1200bps_touch') == 'true':
do_touch = True
return do_touch |
def axis2cat(axis):
"""
Axis is the dimension to sum (the pythonic way). Cat is the dimension that
remains at the end (the Keops way).
:param axis: 0 or 1
:return: cat: 1 or 0
"""
if axis in [0, 1]:
return (axis + 1) % 2
else:
raise ValueError("Axis should be 0 or 1.") |
def submissions(request):
"""smth."""
return {
'id': 'submissions',
'title': 'Submissions',
'href': '/submissions',
} |
def sorted_words(i):
"""
>>> sorted_words("the cat sat on the mat")
'cat mat on sat the the'
"""
words = i.split(' ')
if len(words) == 1:
return i
else:
return ' '.join(sorted(words)).strip() |
def areinstances(objects, classes):
"""Return whether all of the objects are instances of the classes."""
return all(isinstance(obj, classes) for obj in objects) |
def _FormAdj_w(a1, a2):
"""
Transform Eisenstein Integer a1+a2*w -> (-w)^i * (x+y*w)
x+y*w is primary element
assume that a1+a2*w is not divisible 1-w
"""
if a1 % 3 == 0:
if ((a2 % 3) == 2) or ((a2 % 3) == -1):
return a1 - a2, a1, 1
elif ((a2 % 3) == 1) or ((a2 % 3) == -2):
return a2 - a1, -a1, 4
elif ((a1 % 3) == 1) or ((a1 % 3) == -2):
if ((a2 % 3) == 1) or ((a2 % 3) == -2):
return a2, a2 - a1, 5
elif a2 % 3 == 0:
return a1, a2, 0
else:
if ((a2 % 3) == 2) or ((a2 % 3) == -1):
return -a2, a1 - a2, 2
elif a2 % 3 == 0:
return -a1, -a2, 3 |
def find_biggest(arr):
"""Return the address of the biggest element in an array.
Args:
arr: a Python iterable
Returns:
int: index of the biggest element
"""
# Store the first element and assume it's the biggest
biggest = arr[0]
biggest_index = 0
# Loop over every element in the array
for i in range(1, len(arr)):
# Check if the new element from the array is bigger
if arr[i] < biggest:
# Update the 'biggest' variables
biggest = arr[i]
biggest_index = i
# Return the address of the biggest element from the array
return biggest_index |
def bond_check(atom_distance, minimum_length=0, maximum_length=1.5):
"""
Check if distance is bond.
Distance is a bond if it is between the minimum and maximum length.
Parameters
----------
atom_distance: float
The distance between two atoms
minimum_length: float
The minimum length for a bond
maximum_length: float
The maximum length for a bond
Returns
-------
bool
True if bond, False otherwise
"""
if atom_distance > minimum_length and atom_distance <= maximum_length:
return True
else:
return False |
def merge_overlapping_dicts( dicts ):
"""
Merge a list of dictionaries where some may share keys but where
the value must be the same
"""
result = {}
for mapping in dicts:
for key, value in mapping.items():
if key in result and result[ key ] != value:
raise Exception(
"Key `{}` maps to both `{}` and `{}`".format(
key, value, result[ key ] ) )
result[ key ] = value
return result |
def normalize_to_tuple(obj):
"""
If obj is a tuple, return it as-is; otherwise, return it in a tuple with it
as its single element.
"""
if obj is not None:
if isinstance(obj, (list, tuple)):
return tuple(obj)
return (obj, )
return tuple() |
def _has_base(cls, base):
"""Helper for _issubclass, a.k.a pytypes.issubtype.
"""
if cls is base:
return True
elif cls is None:
return False
try:
for bs in cls.__bases__:
if _has_base(bs, base):
return True
except:
pass
return False |
def perform_bitwise_and(ip, mask):
"""
Performs bitwise AND operation on given two binary strings
:pre: length of two binary strings should be identical
:param ip: First binary string
:param mask: First binary string
:return: Binary string after Bitwise AND operation
"""
result = ""
for i in range(len(ip)):
result += str(int(ip[i], 2) & int(mask[i], 2))
return result |
def count_change(amount):
"""Return the number of ways to make change for amount.
>>> count_change(7)
6
>>> count_change(10)
14
>>> count_change(20)
60
>>> count_change(100)
9828
"""
def helper(amt, min_coin_value):
if amt < 0:
return 0
elif amt == 0:
return 1
elif min_coin_value > amt:
return 0
else: # we either subtract min coin value from amount or double the min coin value
return helper(amt - min_coin_value, min_coin_value) + helper(amt, min_coin_value * 2)
return helper(amount, 1) |
def replace_insensitive(string, target, replacement):
"""
Similar to string.replace() but is case insensitive
Code borrowed from: http://forums.devshed.com/python-programming-11/case-insensitive-string-replace-490921.html
"""
no_case = string.lower()
index = no_case.rfind(target.lower())
if index >= 0:
return string[:index] + replacement + string[index + len(target):]
else: # no results so return the original string
return string |
def g(i, k, l):
"""
Stage cost
:param i: state
:param k: control
:param l: switching
:return: the cost
"""
if i == 65535:
return 1
return 5 |
def points_to_vec(pt1, pt2, flip = False):
"""
Converts the coordinate of two points (pt1 > pt2) to a vector
flip: bool, default = False
If the coordinate system should be flipped such that higher y-coords
are lower (e.g. needed when working with images in opencv).
"""
vx = pt2[0] - pt1[0]
vy = pt1[1] - pt2[1] if flip else pt2[1] - pt1[1]
return vx, vy |
def replicate_recur(times, data):
"""
Will recursively repeat data a number of times.
:param times: the number of times to repeate the data
:param data: item to be repeated
:return: data to be repeated a number of times.
:rtype: list
"""
if isinstance(data, (float, int, str)) and isinstance(times, int):
if times > 0:
ls = replicate_recur(times - 1, data)
ls.append(data)
return ls
else:
return []
else:
raise ValueError |
def switch_interface_config_select_trunk(switch_interface_config):
"""Select and return all switch interfaces which are trunk links.
Interfaces are assumed to be trunked, unless they have a ngs_trunk_port
item which is set to False.
:param switch_interface_config: Switch interface configuration dict
"""
return {
name: config
for name, config in switch_interface_config.items()
if config.get('ngs_trunk_port', True)
} |
def authorRank (authors, lastname, forename, initials):
""" get the position of a person in an author list, first do first name
matching, then in a second loop try matching of initials.
"""
i=0
retlist=[]
for a in authors:
i+=1
#if a['AffiliationInfo']:
# print ("Affiliation: ", a['AffiliationInfo'][0]['Affiliation'])
if 'LastName' in a and lastname:
if 'ForeName' in a:
#print ("FORENAME", a['ForeName'], forename)
if a['LastName'].lower() == lastname.lower() and \
(forename.lower() in a['ForeName'].lower() \
or a['ForeName'].lower() in forename.lower()):
#retlist = [i, a['LastName'] + ' ' + a['ForeName'] + ' (' + a['Initials'] + ')']
retlist = [i, a['LastName'] + ' ' + a['ForeName']]
if len(retlist) > 0:
return retlist
i=0
for a in authors:
i+=1
if 'LastName' in a:
if 'Initials' in a:
#print("LAST", a['LastName'], lastname)
if a['LastName'].lower() == lastname.lower() and initials.lower() \
in a['Initials'].lower():
retlist = [i, a['LastName'] + ' ' + a['Initials']]
if len(retlist) > 0:
return retlist
else:
return 0, "" |
def is_superset_of(value, superset):
"""Check if a variable is a superset."""
return set(value) <= set(superset) |
def parse_define(define):
"""Parses 'FOO=[BAR|BAZ]' into (FOO, [BAR, BAZ])."""
macro, choices = define.split("=")
choices = choices.strip("[]").split("|")
return (macro, choices) |
def AVG(src_column):
"""
Builtin average aggregator for groupby. Synonym for tc.aggregate.MEAN. If
src_column is of array type, and if array's do not match in length a NoneType is
returned in the destination column.
Example: Get the average rating of each user.
>>> sf.groupby("user",
... {'rating_avg':tc.aggregate.AVG('rating')})
"""
return ("__builtin__avg__", [src_column]) |
def center(longitude):
"""
Ensure longitude is within -180 to +180
"""
return ((longitude + 180.0) % 360) - 180.0 |
def square_of_sums(n):
""" returns the square of sums of first n numbers """
iter = 1
sum = 0
while iter <= n:
sum += iter
iter += 1
return sum**2 |
def pad(array, desired_length, default_value):
"""Pads the input array to a given length with the supplied value."""
return array + [default_value] * (desired_length - len(array)) |
def quadratic_roots(a, b, c):
"""
Returns a tuple containg the roots of the quadratic equation ax^2+bx+c
If the roots are imaginary then an error message is displayed and None is returned
"""
D = (b**2) - (4 * a * c)
if D<0:
print("Imaginary roots")
return None
else:
num1=-b+(D**(1/2))
num2=-b-(D**(1/2))
denum=2*a
return (num1/denum, num2/denum) |
def v13_add(*matrices):
"""Add corresponding numbers in given 2-D matrices."""
try:
from itertools import zip_longest
return [
[sum(values) for values in zip_longest(*rows)]
for rows in zip_longest(*matrices)
]
except TypeError as e:
raise ValueError("Given matrices are not the same size.") from e |
def build_label(vertex_id, agents):
"""Builds the emoji representation of all agents on a single vertex"""
return f"{vertex_id}" + "".join(agent.emojify() for agent in agents) |
def mean(l):
"""Take mean of array like."""
return sum(l) / len(l) |
def minmax_naive(a):
"""Find mix & max in a list by naive algorithm.
- Time complexity: O(n).
- Space complexity: O(1).
"""
_min = a[0]
_max = a[0]
for i in range(1, len(a)):
if a[i] < _min:
_min = a[i]
if a[i] > _max:
_max = a[i]
return [_min, _max] |
def parse_info_date_str(info_date_str):
"""Returns an info_date string modified in such a way that Elasticsearch would not attempt to interpret it as a date.
Currently there are several different formats of info_date used.
If no modification is applied Elasticseach will interpret part of the values as a string and another part as a date
which causes a value error and should be avoided.
:param info_date_str:
:return:
"""
return 'str:' + info_date_str |
def deduplicate_list(lst):
""" De-duplicates the given list by converting it to a set then back to a list.
NOTES:
* The list must contain 'hashable' type elements that can be used in sets.
* The result list might not be ordered the same as the input list.
* This will also take tuples as input, though the result will be a list.
:param lst: list to de-duplicate
:return: de-duplicated list
"""
return list(set(lst)) |
def gradFun(x, f, J):
"""The naive example with grad"""
y = f(x)
g = J(x)
return y, g |
def compare_embeddings(image_emb, reference_emb, threshold=2):
"""A mock function for the appropriate comparison of embeddings."""
return abs(image_emb - reference_emb) < threshold |
def isfile(path, **kwargs):
"""Check if *path* is a file"""
import os.path
return os.path.isfile(path, **kwargs) |
def extract_post_history_attributes(dict_elem):
"""
Select the attributes of interest from the post history attribute dict.
:param dict_elem: dict with parsed XML attributes
:return: dict with selection of parsed XML attributes
"""
if 'Text' in dict_elem:
text = dict_elem['Text']
else:
text = ""
return {
'PostId': int(dict_elem['PostId']),
'CreationDate': dict_elem['CreationDate'],
'Text': text
} |
def _parse_intervals(durations):
"""Parse the given durations.
Args:
durations (dict): A dictionary of the each frame duration.
Returns:
A tuple of:
* A list each element of which marks the start time
of the next frame.
* The total animation length.
"""
result, time_ = [], 0
for _, duration in durations.items():
time_ += duration
result.append(time_)
return result, time_ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.