content stringlengths 42 6.51k |
|---|
def get_product_classname(product_data):
"""Get the name of the produt's object class based on the its type and asset class
Args
----
product_data: dict
The product's data in the product_data dict, containing the product's type and possibly its asset class
Return
------
classname: str
The name of the product's object class
"""
product_type = product_data["type"]
product_asset_class = product_data["asset_class"]
if product_type == "ETF" and product_asset_class == "Equity":
return "Equity_ETF"
elif product_type == "ETF" and product_asset_class == "Fixed Income":
return "Fixed_Income_ETF"
elif product_type == "Index" and product_asset_class == "Equity":
return "Equity_Index" |
def count_digits(n):
"""Counts the number of digits in `n`
Test cases:
- 057
"""
if n == 0:
return 1
num_digits = 0
while n > 0:
num_digits += 1
n /= 10
return num_digits |
def unique_list(l):
"""Returns a list of unique values from given list l."""
x = []
#iterate over provided list
for a in l:
#check if number is in new list
if a not in x:
#add it to new list
x.append(a)
return x |
def get_ecr_vulnerability_package_version(vulnerability):
"""
Get Package Version from a vulnerability JSON object
:param vulnerability: dict JSON object consisting of information about the vulnerability in the format
presented by the ECR Scan Tool
:return: str package version
"""
for attribute in vulnerability["attributes"]:
if attribute["key"] == "package_version":
return attribute["value"]
return None |
def near_hundred(n: int) -> bool:
"""Integer n is near 100 or 200 by 10."""
near100 = abs(100 - n) <= 10
near200 = abs(200 - n) <= 10
return any((near100, near200,)) |
def _get_union_pressures(pressures):
""" get list of pressured where rates are defined for both mechanisms
"""
[pr1, pr2] = pressures
return list(set(pr1) & set(pr2)) |
def makeTuple(rect):
"""
Take in rectangle coordinates as list and return as tuple
"""
rectTuple = (rect[0], rect[1], rect[2], rect[3])
return rectTuple |
def sort_at(nl, lis, k, a=0):
"""
[-1,1,0,0,0,0,-1,1]
"""
mind = 0
mval = 0
vlis = []
for i in range(0, len(nl)-k + 1 - a):
v = abs(sum(nl[i:i+k]))
vlis.append(v)
if(v > mval and v != 0):
mval = v
mind = i
return mind, max(lis) != 0 |
def parse_enums(code):
"""
Parses code and returns a list of enums.
Usage:
For this function to work properly
input code needs to be prepared first,
function prepare_for_parsing(code)
has to be called to pre-process the code first.
Input arguments:
code -- code from which we are parsing enums
Output:
List of enums.
Each enum has:
name -- name of enum (located between '} ' and ';')
elements -- list of elements (located between '{' and '}'
and separated by comma)
Each element has:
name -- name of the element
value -- value of the element (only if the
element has value)
Example:
>>> code = '''typedef enum mode {
... NEVER = 0,
... ALWAYS = 2
... } mode_t;'''
>>> code = prepare_for_parsing(code)
>>> print code
typedef enum mode {NEVER = 0,ALWAYS = 2}mode_t;
>>> print parse_enums(code)
[{'elements': [{'name': 'NEVER', 'value': '0'}, {'name': 'ALWAY
S', 'value': '2'}], 'name': 'mode_t'}]
"""
def parse_element(element):
"""
Parses element and returns name and value (optional) of element
Input arguments:
element -- element which we are parsing
Output:
Dictionary with name and value (if there was one)
Example:
>>> element = 'MAX_DEBUG_NEVER = 0'
>>> print parse_element(element)
{'name': 'MAX_DEBUG_NEVER', 'value': '0'}
>>> element = 'MAX_NET_CONNECTION_QSFP_MID_10G_PORT2'
>>> print parse_element(element)
{'name': 'MAX_NET_CONNECTION_QSFP_MID_10G_PORT2'}
"""
if '=' in element:
return {'name': element[ : element.find('=')],
'value': element[element.find('=') + 1 : ]}
else:
return {'name': element}
return [{'name': line[line.find('}') + 1 : line.find(';')],
'elements': [parse_element(element)
for element
in line[line.find('{') + 1 :
line.find('}')].split(',')]}
for line
in code.splitlines()
if 'typedef enum' in line] |
def filter_func(token):
"""
:param token: (str) word or part of word after tokenization
:return: (str) token as a word or part of word (whithout extra chars)
"""
if token == '[UNK]':
token = ''
symbols = ['\u2581', '#'] #chars that need to be filtered out (e. g. '#' for BERT-like tokenization)
for symbol in symbols:
token = token.lstrip(symbol)
return token |
def pad(s, n, p = " ", sep = "|", align = "left"):
"""
Returns a padded string.
s = string to pad
n = width of string to return
sep = separator (on end of string)
align = text alignment, "left", "center", or "right"
"""
if align == "left":
return (s + (p * n))[:n] + sep
elif align == "center":
pos = n + len(s)/2 - n/2
return ((p * n) + s + (p * n))[pos:pos + n] + sep
elif align == "right":
return ((p * n) + s)[-n:] + sep |
def split_detail(detail):
"""
split detail
:param detail:
:return:
"""
info_list = detail.split("*")
if len(info_list) >= 2:
return "\t".join(info_list)
return "" |
def weighted_average(values):
"""Calculates an weighted average
Args:
values (Iterable): The values to find the average as an iterable of
``(value, weight)`` pairs
Returns:
The weighted average of the inputs
Example:
>>> weighted_average([(1, 2), (2, 3)])
1.6
"""
if any(weight < 0 for _, weight in values):
raise ValueError("Weights cannot be less than zero")
dividend, divisor = 0, 0
for value, weight in values:
dividend += value * weight
divisor += weight
res = dividend / divisor
if res == int(res):
return int(res)
return res |
def wxyz2xyzw(wxyz):
"""Convert quaternions from WXYZ format to XYZW."""
w, x, y, z = wxyz
return x, y, z, w |
def make_pseudonumber_sortable(pseudonumber):
"""For a quantity that may or may not be numeric, return something that is partially numeric.
The method must always return a tuple containing a number, then zero or more strings.
Other parts of the program assume that the first number is the numeric representation of the quantity given.
"""
# For the normal case (a number), just return the number
if pseudonumber.isdigit():
return (int(pseudonumber),)
# Empty string: return 0
if not pseudonumber:
return (0,)
# Otherwise, remove any prefix, then return (number, prefix, suffix)
# (if it's entirely text, return (0, string))
num_idx = 0
while num_idx < len(pseudonumber) and not pseudonumber[num_idx].isdigit():
num_idx += 1
if num_idx == len(pseudonumber):
return (0, pseudonumber)
suf_idx = num_idx
while suf_idx < len(pseudonumber) and pseudonumber[suf_idx].isdigit():
suf_idx += 1
pre = pseudonumber[:num_idx]
num = pseudonumber[num_idx:suf_idx]
suf = pseudonumber[suf_idx:]
return (int(num), pre, suf) |
def sequence_id(data: list, ids: list) -> list:
"""
Filter out images that do not have the sequence_id in the list of ids
:param data: The data to be filtered
:type data: list
:param ids: The sequence id(s) to filter through
:type ids: list
:return: A feature list
:rtype: list
"""
return [feature for feature in data if feature["properties"]["sequence_id"] in ids] |
def get_target_for_label(label):
"""Converted a label to `0` or `1`.
Args:
label(string) - Either "POSITIVE" or "NEGATIVE".
Returns:
`0` or `1`.
"""
if(label == 'POSITIVE'):
return 1
else:
return 0 |
def format_time(mp):
"""Convert minutes played from analog time to digital time.
:param str mp: minutes played, e.g. '24:30'
:return int: e.g. 24.5
"""
(m, s) = mp.split(':')
digital = int(m) + int(s) / 60
return round(digital, 1) |
def _metdata_filter(img_metadata, filters, img_pass):
"""Check if an image metadata value matches a filter value.
Args:
img_metadata: The metadata value for the given image
filters: The metadata filter values
img_pass: The current pass/fail state
:param img_metadata: str
:param filters: str or list
:param img_pass: int
:return img_pass: int
"""
if isinstance(filters, list):
# list of multiple filters
if img_metadata not in filters:
img_pass = 0
else:
# single filter as string
if img_metadata != filters:
img_pass = 0
return img_pass |
def _float_parameter(level: float, maxval: float):
"""Helper function to scale a value between ``0`` and ``maxval`` and return as a float.
Args:
level (float): Level of the operation that will be between [0, 10].
maxval (float): Maximum value that the operation can have. This will be scaled to
level/10.
Returns:
float: The result from scaling ``maxval`` according to ``level``.
"""
return float(level) * maxval / 10. |
def rfact(n):
"""Recursive"""
return rfact(n - 1) * n if n > 1 else 1 |
def is_collade(v1, v2):
"""
Input:
v1,v2: velocity of train one and train two respectively in km/h
Output:
True if trains collade under defined circumstates, False if not
"""
t1 = 4/v1
s1 = t1*v2
if s1 >= 6:
return True
else:
return False |
def summation(num) -> int:
"""This function makes numbers summation."""
return sum(range(1, num + 1)) |
def num_to_letter(n):
"""Inverse of letter_to_num"""
return chr(n + 97) |
def transform_diag_element(element, file_ids_to_remove, new_file_ids):
"""
This function will update every file attribute of the given diagnostic
element.
On the first call it will get a diagnostic section dictionary and
recursively traverse all children of it. If the child element is a file
attribute it will update it by using the 'new_file_ids' dictionary.
It will return False if one of the file attribute is in the removable file
list. Otherwise it will return True.
"""
if isinstance(element, dict):
for k, v in element.items():
if k == 'file':
if v in file_ids_to_remove:
return False
else:
element['file'] = new_file_ids[v]
else:
if not transform_diag_element(v, file_ids_to_remove,
new_file_ids):
return False
elif isinstance(element, list) or isinstance(element, tuple):
for v in element:
if not transform_diag_element(v, file_ids_to_remove, new_file_ids):
return False
return True |
def toggleMonths2(click):
"""
When syncing years, there should only be one time slider
"""
if not click:
click = 0
if click % 2 == 0:
style = {"display": "none", "margin-top": "0", "margin-bottom": "80"}
else:
style = {"margin-top": "30", "margin-bottom": "30"}
return style |
def density(tab):
"""Return for a given grid the proportion of filled holes among all holes
after percolation
Args:
tab (array): grid
Returns:
float: proportion of filled holes
"""
n = len(tab)
holes = 0
filled = 0
for i in range(n):
for j in range(n):
if tab[i][j] == 1.0:
holes = holes + 1
elif tab[i][j] == 0.5:
filled = filled + 1
holes = holes + 1
if holes == 0:
return 0
else:
return filled / holes |
def timeFix(s,m,h):
"""
Fixes time to ensure it stays within normal range (0-60)
"""
if(s>=60 or m>=60):
while(s>=60 or m>=60):
if s >= 60:
m+=1
s-=60
if m >= 60:
h+=1
m-=60
elif(s<0 or m<0):
while(s<0 or m<0):
if s < 0:
m-=1
s+=60
if m < 0:
h-=1
m+=60
return s,m,h |
def hash_fold(item, tablesize):
"""
The folding method for constructing hash functions begins by dividing the item into equal-size
pieces (the last piece may not be of equal size). These pieces are then added together to give
the resulting hash value. For example, if our item was the phone number 436-555-4601, we would
take the digits and divide them into groups of 2 (43,65,55,46,01). After the addition,
43+65+55+46+0143+65+55+46+01, we get 210. If we assume our hash table has 11 slots, then we
need to perform the extra step of dividing by 11 and keeping the remainder. In this case
210 % 11210 % 11 is 1, so the phone number 436-555-4601 hashes to slot 1.
item - a number
tablesize
"""
# Split number into n chunks
n = 2
number = str(item)
chunked_list = [number[i:i+n] for i in range(0, len(number), n)]
# Convert the list items to numbers then get the sum
sum = 0
for c in chunked_list:
sum += int(c)
return sum % tablesize |
def dependencies(metadata_dict, field='depends'):
"""Returns a dictionary of (str, str) based on metadata's dependency field.
The keys indicate the name of a package (shorthand name or full git URL).
The names 'zeek' or 'zkg' may also be keys that indicate a dependency on a
particular Zeek or zkg version.
The values indicate a semantic version requirement.
If the dependency field is malformed (e.g. number of keys not equal to
number of values), then None is returned.
"""
if field not in metadata_dict:
return dict()
rval = dict()
depends = metadata_dict[field]
parts = depends.split()
keys = parts[::2]
values = parts[1::2]
if len(keys) != len(values):
return None
for i, k in enumerate(keys):
if i < len(values):
rval[k] = values[i]
return rval |
def is_off(filename):
"""Checks that the file is a .off file
Only checks the extension of the file
:param filename: path to the file
"""
return filename[-4:] == '.off' |
def to_hex2(i):
"""Converts an integer to hex form (with 2 digits)."""
tmp = hex(i)[2:]
if len(tmp) == 1:
return "0" + tmp
else:
return tmp |
def example_func(param1, param2):
"""Example function with types documented in the docstring
Args:
param1 (int): The first parameter
param2 (str): The second parameter
Returns:
bool: The return value. True for success, False otherwise.
"""
print(param1)
print(param2)
return True |
def unique(content):
"""Takes an iter and find the unique elements and return the simplified iter
:param content: iter
Any iter that can be converted to a set
:returns: iter
an iter of same type but with only unique elements
"""
the_type = type(content)
return the_type(set(content)) |
def ByteToHex( byteStr ):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
# Uses list comprehension which is a fractionally faster implementation than
# the alternative, more readable, implementation below
#
# hex = []
# for aChar in byteStr:
# hex.append( "%02X " % ord( aChar ) )
#
# return ''.join( hex ).strip()
return ''.join( [ "%02X " % ord( x ) for x in byteStr ] ).strip() |
def _value_checker(index_input):
"""Helper function to input check the main index functions"""
if index_input == '': # empty string, default index
return "default"
try:
return float(index_input)
except ValueError:
return False |
def get_item_properties(item, fields, mixed_case_fields=(), formatters=None):
"""Return a tuple containing the item properties.
:param item: a single item resource (e.g. Server, Tenant, etc)
:param fields: tuple of strings with the desired field names
:param mixed_case_fields: tuple of field names to preserve case
:param formatters: dictionary mapping field names to callables
to format the values
"""
if formatters is None:
formatters = {}
row = []
for field in fields:
if field in formatters:
row.append(formatters[field](item))
else:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
if not hasattr(item, field_name) and \
(isinstance(item, dict) and field_name in item):
data = item[field_name]
else:
data = getattr(item, field_name, '')
if data is None:
data = ''
row.append(data)
return tuple(row) |
def GetSymbolsFromReport(report):
"""Extract all symbols from a suppression report."""
symbols = []
prefix = "fun:"
prefix_len = len(prefix)
for line in report.splitlines():
index = line.find(prefix)
if index != -1:
symbols.append(line[index + prefix_len:])
return symbols |
def count_trailing_newlines(s):
"""count number of trailing newlines
this includes newlines that are separated by other whitespace
"""
return s[len(s.rstrip()):].count('\n') |
def get_best(current, candidate):
""" Return the new bunnies saved if the given candidate did saved
more bunnies than the current
Args:
current (list[int]): sorted list of bunnies
candidate (set[int]): unordered collection of saved bunnies
Return:
list[int]: bunnies saved sorted by ids
"""
if len(candidate) > len(current): # Better state
return sorted(list(candidate))
elif len(candidate) == len(candidate): # Should check the individuals ids
candidate = sorted(list(candidate))
for i in range(len(current)):
if current[i] < candidate[i]: # We stop at the first id we found
return current
elif current[i] > candidate[i]:
return candidate
return current |
def _cpp_field_name(name):
"""Returns the C++ name for the given field name."""
if name.startswith("$"):
dollar_field_names = {
"$size_in_bits": "IntrinsicSizeInBits",
"$size_in_bytes": "IntrinsicSizeInBytes",
"$max_size_in_bits": "MaxSizeInBits",
"$min_size_in_bits": "MinSizeInBits",
"$max_size_in_bytes": "MaxSizeInBytes",
"$min_size_in_bytes": "MinSizeInBytes",
}
return dollar_field_names[name]
else:
return name |
def nll_has_variance(nll_str):
""" A simple helper to return whether we have variance in the likelihood.
:param nll_str: the type of negative log-likelihood.
:returns: true or false
:rtype: bool
"""
nll_map = {
'gaussian': True,
'laplace': True,
'pixel_wise': False,
'l2': False,
'msssim': False,
'bernoulli': False,
'l2msssim': False,
'log_logistic_256': True,
'disc_mix_logistic': True
}
assert nll_str in nll_map
return nll_map[nll_str] |
def _check_issue_label(label):
"""
Ignore labels that start with "Status:" and "Resolution:". These labels are
mirrored from Jira issue and should not be mirrored back as labels
"""
ignore_prefix = ("status:", "resolution:")
if label.lower().startswith(ignore_prefix):
return None
return label |
def __eingroup_shapes(in_groups, out_groups, dim):
"""Return shape the input needs to be reshaped, and the output shape."""
def shape(groups, dim):
return [group_dim(group, dim) for group in groups]
def product(nums):
assert len(nums) > 0
result = 1
for num in nums:
result *= num
return result
def group_dim(group, dim):
try:
return product([dim[g] for g in group])
except KeyError as e:
raise KeyError("Unknown dimension for an axis {}".format(e))
out_shape = shape(out_groups, dim)
in_groups_flat = []
for group in in_groups:
for letter in group:
in_groups_flat.append(letter)
in_shape_flat = shape(in_groups_flat, dim)
return in_shape_flat, out_shape |
def friend(names):
"""Return list of friends with name lenght of four."""
result = []
for name in names:
if len(name) == 4:
result.append(name)
return result |
def connect(endpoint=None):
"""Generate connect packet.
`endpoint`
Optional endpoint name
"""
return u'1::%s' % (
endpoint or ''
) |
def humedad_solidos(Xs,z,k,Xe,M,S):
"""this is the rhs of the ODE to integrate, i.e. dV/dt=f(V,t)"""
'''
Xs: Solid moisture []
z: Dimensionless position []
k: Drying constant
Xe: Equilibrium moisture []
M: Total load [kg]
S: Solid flow in [kg/s]
'''
return -((k*(Xs-Xe))*M)/S |
def vardim2var(vardim):
"""
Extract variable name from 'variable (dim1=ndim1,)' string.
Parameters
----------
vardim : string
Variable name with dimensions, such as 'latitude (lat=32,lon=64)'.
Returns
-------
string
Variable name.
Examples
--------
>>> vardim2var('latitude (lat=32,lon=64)')
latitude
"""
return vardim[0:vardim.rfind('(')].rstrip() |
def concat_maybe_tuples(vals):
"""
>>> concat_maybe_tuples([1, (2, 3)])
(1, 2, 3)
"""
result = []
for v in vals:
if isinstance(v, (tuple, list)):
result.extend(v)
else:
result.append(v)
return tuple(result) |
def reverse_dict(d):
"""Reverses direction of dependence dict
>>> d = {'a': (1, 2), 'b': (2, 3), 'c':()}
>>> reverse_dict(d) # doctest: +SKIP
{1: ('a',), 2: ('a', 'b'), 3: ('b',)}
:note: dict order are not deterministic. As we iterate on the
input dict, it make the output of this function depend on the
dict order. So this function output order should be considered
as undeterministic.
"""
result = {} # type: ignore[var-annotated]
for key in d:
for val in d[key]:
result[val] = result.get(val, tuple()) + (key, )
return result |
def get_cfg_sec_dict(cfg, sec, convert='float', verbose=False):
"""
Retrieve a dictionary of a section with options as keys and corresponding
values.
Parameters
----------
cfg : configparser.ConfigParser()
Configuration as retrieved by the function read_cfg_file().
sec : str
The section in which the options are located.
convert : str
The type of the values of the options.
verbose : bool, optional
no function so far ...
Returns
-------
dict
Includes all options (keys) and values from the section selected
{ key: value }
"""
sec_dic = {}
if sec in cfg:
options = cfg[sec]
for key, value in options.items():
try:
if convert == 'int':
sec_dic[key] = options.getint(key)
elif convert == 'float':
sec_dic[key] = options.getfloat(key)
elif convert == 'boolean':
sec_dic[key] = options.getboolean(key)
else:
sec_dic[key] = value
except:
sec_dic[key] = value
return sec_dic |
def strip_dot_from_keys(data: dict, replace_char='#') -> dict:
""" Return a dictionary safe for MongoDB entry.
ie. `{'foo.bar': 'baz'}` becomes `{'foo#bar': 'baz'}`
"""
new_ = dict()
for k, v in data.items():
if type(v) == dict:
v = strip_dot_from_keys(v)
if '.' in k:
k = k.replace('.', replace_char)
new_[k] = v
return new_ |
def _get_prop(properties: list, key: str):
"""
Get a property from list of properties.
:param properties: The list of properties to filter on
:param key: The property key
:return:
"""
result = list(filter(lambda prop: prop["name"] == key, properties))
if len(result) == 0:
raise ValueError(f"Failed to find {key} in property set")
return result[0]["value"] |
def xor(s1, s2):
"""
Exclusive-Or of two byte arrays
Args:
s1 (bytes): first set of bytes
s2 (bytes): second set of bytes
Returns:
(bytes) s1 ^ s2
Raises:
ValueError if s1 and s2 lengths don't match
"""
if len(s1) != len(s2):
raise ValueError('Input not equal length: %d %d' % (len(s1), len(s2)))
return bytes(a ^ b for a, b in zip(s1, s2)) |
def find_net_from_node(node, in_dict, in_keys):
"""
Return the net name to which the given node is attached.
If it doesn't exist, return None
"""
for k in in_keys:
if node in in_dict[k]:
return k |
def _retry_matcher(details):
"""Matches retry details emitted."""
if not details:
return False
if 'retry_name' in details and 'retry_uuid' in details:
return True
return False |
def inherits_init(cls):
"""Returns `True` if the class inherits its `__init__` method.
partof: #SPC-notify-inst.inherits
"""
classname = cls.__name__
suffix = f"{classname}.__init__"
return not cls.__init__.__qualname__.endswith(suffix) |
def isclose(a, b):
"""adapted from here: https://stackoverflow.com/a/33024979/2260"""
rel_tol = 1e-09
abs_tol = 0.0
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) |
def make_bold(text):
"""Make text bold before sending to the telegram chat."""
return f'<b>{text}</b>' |
def type_name(item):
"""
----
examples:
1) type_name('apple') -> 'str'
----
:param item:
:return:
"""
return type(item).__name__ |
def strip_new_line(str_json):
"""
Strip \n new line
:param str_json: string
:return: string
"""
str_json = str_json.replace('\n', '') # kill new line breaks caused by triple quoted raw strings
return str_json |
def construct_ecosystem(species, ecosystem):
"""Return A list of lists (interaction matrix) with the interaction parameters from the ecosystem dictionary.
Each list contains the ordered interaction parameters
with all other species for a focal species. The order is defined by alphabetically ordered species.
Parameters
----------
species : list, species names
ecosystem : dict, contains interactions for all species
Returns
----------
A : list of lists, interaction matrix
"""
A = [[ecosystem[s][ss] for ss in sorted(species)] for s in sorted(species)]
return A |
def gray_augment(is_training=True, **kwargs):
"""Applies random grayscale augmentation."""
if is_training:
prob = kwargs['prob'] if 'prob' in kwargs else 0.2
return [('gray', {'prob': prob})]
return [] |
def tcol(ui_cols):
"""two column value"""
tcol = "_".join(ui_cols.keys())
return tcol |
def compare_test_pairs(test_pairs, compare_function):
"""For each of the entries in test_pairs, the supplied compare_function is run on the 'ground_truth' and
'test_input' values and added as the 'results' value in a dictionary keyed by the pair 'name'"""
results = {}
for pair in test_pairs:
ground_truth = test_pairs[pair]['ground_truth']
test_input = test_pairs[pair]['test_input']
results[test_pairs[pair]['name']] = {'results': compare_function(ground_truth, test_input)}
return results |
def _serialize_tag(tag: int):
"""Serializes tag to bytes"""
if tag <= 0xff:
return bytes([tag])
elif tag <= 0xffff:
return bytes([tag >> 8, tag & 0xff])
elif tag <= 0xffffff:
return bytes([tag >> 16, (tag >> 8) & 0xff, tag & 0xff])
raise RuntimeError("Unsupported TLV tag") |
def dirname(p):
"""Returns the directory component of a pathname"""
i = p.rfind('/') + 1
assert i >= 0, "Proven above but not detectable"
head = p[:i]
if head and head != '/'*len(head):
head = head.rstrip('/')
return head |
def parse_dimensions(descr):
"""
Parse a list of dimensions.
"""
return set(int(value) for value in descr.split(",") if value.strip() != "") |
def IsDict(inst):
"""Returns whether or not the specified instance is a dict."""
return hasattr(inst, 'iteritems') |
def g_iter(n):
"""Return the value of G(n), computed iteratively.
>>> g_iter(1)
1
>>> g_iter(2)
2
>>> g_iter(3)
3
>>> g_iter(4)
10
>>> g_iter(5)
22
>>> from construct_check import check
>>> # ban recursion
>>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion'])
True
"""
"*** YOUR CODE HERE ***"
if n <= 3:
return n
else:
pre2, pre1, cur = 1, 2, 3
k = 1
while k <= n - 3:
pre2, pre1, cur = pre1, cur, cur + 2 * pre1 + 3 * pre2
k += 1
return cur |
def _toInt(val, replace=()):
"""Return the value, converted to integer, or None; if present, 'replace'
must be a list of tuples of values to replace."""
for before, after in replace:
val = val.replace(before, after)
try:
return int(val)
except (TypeError, ValueError):
return None |
def __prefixNumber(num, leading):
"""
Prefixes "num" with %leading zeroes.
"""
length = int(leading)+1
num = str(num)
while len(num) < length:
num = '0' + num
return num |
def path_type(value):
"""Path value routing."""
print(value)
return "correct" |
def cmp_floats(a, b):
"""NOTE: This code came from here: https://github.com/danieljfarrell/pvtrace/blob/master/pvtrace/Geometry.py""" #noqa
abs_diff = abs(a-b)
if abs_diff < 1e-12:
return True
else:
return False |
def build_error(non_accessible_datasets):
""""
Fills the `error` part in the response.
This error only applies to partial errors which do not prevent the Beacon from answering.
"""
message = f'You are not authorized to access some of the requested datasets: {non_accessible_datasets}'
return {
'error': {
'errorCode': 401,
'errorMessage': message
}
} |
def filter_any_answer(group):
"""Filter questions answered by anyone in group."""
answers = set()
for person in group:
for question in person:
answers.add(question)
return answers |
def merge(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs): # If xs list is finished,
result.extend(ys[yi:]) # Add remaining items from ys
return result # And we're done.
if yi >= len(ys): # Same again, but swap roles
result.extend(xs[xi:])
return result
# Both lists still have items, copy smaller item to result.
if xs[xi] <= ys[yi]:
result.append(xs[xi])
xi += 1
else:
result.append(ys[yi])
yi += 1 |
def theta_map(mat, z):
"""
Evaluates the conformal map "theta" defined by a matrix [a,b],[c,d]
theta = (a*z + b)/(c*z + d).
"""
[a, b], [c, d] = mat
return (a*z + b)/(c*z + d) |
def is_variable_name(test_str: str):
"""Is the test string a valid name for a variable or not?
Arguments:
test_str (str): Test string
Returns:
bool: Is str a variable name
"""
return test_str.isidentifier() |
def unify_sex(sex):
"""Maps the sex of a patient into one of the following values: "M", "F" or
``None``.
Parameters
----------
sex : str
Sex of the patient.
Returns
-------
sex : str
Transformed sex of the patient.
"""
transform_dict = {
"MALE": "M",
"M": "M",
"FEMALE": "F",
"F": "F",
}
return transform_dict.get(sex) |
def _from_yaml_to_func(method, params):
"""go from yaml to method.
Need to be here for accesing local variables.
"""
prm = dict()
if params is not None:
for key, val in params.items():
prm[key] = eval(str(val))
return eval(method)(**prm) |
def size_uint_var(value: int) -> int:
"""
Return the number of bytes required to encode the given value
as a QUIC variable-length unsigned integer.
"""
if value <= 0x3F:
return 1
elif value <= 0x3FFF:
return 2
elif value <= 0x3FFFFFFF:
return 4
elif value <= 0x3FFFFFFFFFFFFFFF:
return 8
else:
raise ValueError("Integer is too big for a variable-length integer") |
def make_context(host, port, path, store, callbacks,
collection_funcs, retrieve_funcs, entry_funcs,
strip_meta, ctl, queue):
"""Returns a context object which is passed around by visit()."""
return {"host": host, "port": port, "store": store,
"path": path, "queue": queue or [], "ctl": ctl,
"collection_funcs": collection_funcs,
"retrieve_funcs": retrieve_funcs,
"entry_funcs": entry_funcs,
"strip_meta": strip_meta,
"callbacks": callbacks} |
def is_cfn_magic(d):
"""
Given dict `d`, determine if it uses CFN magic (Fn:: functions or Ref)
This function is used for deep merging CFN templates, we don't treat CFN magic as a regular dictionary
for merging purposes.
:rtype: bool
:param d: dictionary to check
:return: true if the dictionary uses CFN magic, false if not
"""
if len(d) != 1:
return False
k = d.keys()[0]
if k == 'Ref' or k.startswith('Fn::') or k.startswith('Rb::'):
return True
return False |
def __is_utf8(rule_string):
"""
Takes the string of the rule and parses it to check if there are only utf-8 characters present.
:param rule_string: the string representation of the yara rule
:return: true if there are only utf-8 characters in the string
"""
try:
rule_string.encode('utf-8')
except UnicodeEncodeError:
return False
else:
return True |
def default_pipeline(pipeline=None):
"""Get default pipeline definiton, merging with input pipline if supplied
Parameters
----------
pipeline : dict, optional
Input pipline. Will fill in any missing defaults.
Returns
-------
dict
pipeline dict
"""
defaults = {
"pipeline": {},
"settings": {},
"output": {"format": "netcdf", "filename": None, "format_kwargs": {}},
# API Gateway
"url": "",
"params": {},
}
# merge defaults with input pipelines, if supplied
if pipeline is not None:
pipeline = {**defaults, **pipeline}
pipeline["output"] = {**defaults["output"], **pipeline["output"]}
pipeline["settings"] = {**defaults["settings"], **pipeline["settings"]}
else:
pipeline = defaults
# overwrite certain settings so that the function doesn't fail
pipeline["settings"]["ROOT_PATH"] = "/tmp"
pipeline["settings"]["LOG_FILE_PATH"] = "/tmp/podpac.log"
return pipeline |
def weighted(x,y,p1,p2):
"""A weighted sum
Args:
x (float): first value
y (float): second value
p1 (float): first weight
p2 (float): second weight
Returns:
float: A weighted sum
"""
tmp = p1*x + p2*y
output = tmp
return output |
def fib_dp_tbl(n: int) -> int:
"""Computes the n-th Fibonacci number.
Args:
n: The number of which Fibonacci sequence to be computed.
Returns:
The n-th number of the Fibonacci sequence.
"""
memo = {0: 0, 1: 1}
for i in range(2, n+1):
memo[i] = memo[i-1] + memo[i-2]
return memo[n] |
def find_x(search_string):
"""find x in the search str:arr; return True if found"""
found = False
for char in search_string:
if char.lower() == 'x':
found = True
break
print(f'Is x in the string? {found}')
return found |
def make_shard_files(dataset_files, num_shards, shard_id):
""" Make sharding files when shard_equal_rows is False. """
idx = 0
shard_files = []
for dataset_file in dataset_files:
if idx % num_shards == shard_id:
shard_files.append((dataset_file, -1, -1, True))
idx += 1
return shard_files |
def _get_plane_coeff(x, y, z):
"""private method: compute plane coefficients in 3D given three points"""
a = ((y[1] - x[1]) * (z[2] - x[2]) -
(z[1] - x[1]) * (y[2] - x[2]))
b = ((y[2] - x[2]) * (z[0] - x[0]) -
(z[2] - x[2]) * (y[0] - x[0]))
c = ((y[0] - x[0]) * (z[1] - x[1]) -
(z[0] - x[0]) * (y[1] - x[1]))
d = -(a * x[0] + b * x[1] + c * x[2])
return a, b, c, d |
def euclidean_distance_sqr(point1, point2):
"""
>>> euclidean_distance_sqr([1,2],[2,4])
5
"""
return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 |
def find_subseq_in_seq(seq, subseq):
"""Return an index of `subseq`uence in the `seq`uence.
Or `-1` if `subseq` is not a subsequence of the `seq`.
The time complexity of the algorithm is O(n*m), where
n, m = len(seq), len(subseq)
from https://stackoverflow.com/questions/425604/best-way-to-determine-if-a-sequence-is-in-another-sequence
"""
i, n, m = -1, len(seq), len(subseq)
try:
while True:
i = seq.index(subseq[0], i + 1, n - m + 1)
if subseq == seq[i:i + m]:
return i
except ValueError:
return -1 |
def hello_world(name: str) -> str:
"""Hello world function
Parameters
----------
name : str
Name to say hi to
Returns
-------
greeting : str
A simple greeting
"""
return f"Hello {name}" |
def value_or_none(value):
"""Return string value if not empty. Otherwise, returns None."""
if value.strip() == "":
return None
return value |
def apply_noise(val_list, noise_params, noise_function):
"""
Applies noise to each value in a list of values and returns the result.
Noise is generated by a user-provided function that maps a value and
parameters to a random value.
"""
result = []
for val, params in zip(val_list, noise_params):
if type(params) is not tuple:
# better be a scalar
params = (params,)
result.append(noise_function(val, *params))
return result |
def _canonicalize_lv_path(lv_path):
"""Convert LV path to a (vg, lv) tuple"""
if lv_path.startswith('/dev'):
# '/dev/vg/lv'
_, _, vg, lv = lv_path.split('/')
else:
# vg/lv
vg, lv = lv_path.split('/')
return vg, lv |
def sum_digits(n):
"""Sum all the digits of n.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
>>> x = sum_digits(123) # make sure that you are using return rather than print
>>> x
6
"""
i = 0
def pow_count(n):
return len(str(n))-1
def digit_count(n):
return n // pow(10, pow_count(n))
while n > 1:
i, n = i + digit_count(n), n - digit_count(n) * pow(10, pow_count(n))
return i |
def wwma_values(values, period=None):
"""Returns list of running Welles Wilder moving averages.
Approximation of the ema.
:param values: list of values to iterate and compute stat.
:param period: (optional) # of values included in computation.
* None - includes all values in computation.
:rtype: list of windowed Welles Wilder moving averages.
Examples:
>>> values = [34, 30, 29, 34, 38, 25, 35]
>>> results = wwma_values(values, 3) #using 3 period window.
>>> ["%.2f" % x for x in results]
['34.00', '32.00', '31.00', '32.00', '34.00', '31.00', '32.33']
"""
if period:
if period < 1:
raise ValueError("period must be 1 or greater")
period = int(period)
results = []
lastval = None
for bar, newx in enumerate(values):
if lastval == None:
lastval = float(newx)
elif (not period) or (bar < period):
lastval = lastval + ((newx - lastval) / (bar + 1.0))
else:
lastval = (newx + lastval * (period - 1.0)) / period
results.append(lastval)
return results |
def add_number_separators(number, separator=' '):
"""
Adds a separator every 3 digits in the number.
"""
if not isinstance(number, str):
number = str(number)
# Remove decimal part
str_number = number.split('.')
if len(str_number[0]) <= 3:
str_number[0] = str_number[0]
else:
str_number[0] = add_number_separators(str_number[0][:-3]) + separator + str_number[0][-3:]
# Verify if the var "number" have a decimal part.
if len(str_number) > 1:
return "%s.%s" % (str_number[0], str_number[1])
return str_number[0] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.