content
stringlengths 42
6.51k
|
---|
def calculate_checksum(message: bytes) -> bytes:
"""Calculates the checksum for a message.
The message should not have a checksum appended to it.
Returns:
The checksum, as a byte sequence of length 2.
"""
return sum(message).to_bytes(2, byteorder='big')
|
def _no_params(param_data):
"""aux func"""
return param_data['title'] == 'None' and \
param_data['description'] == 'None' and \
param_data['url'] == 'None' and \
param_data['issn'] == 'None' and \
param_data['rnps'] == 'None' and \
param_data['year_start'] == 'None' and \
param_data['year_end'] == 'None'
|
def iso8601format(dt):
"""Given a datetime object, return an associated ISO-8601 string"""
return dt.strftime('%Y-%m-%dT%H:%M:%SZ') if dt else ''
|
def digital_root(num, modulo = 9):
""" similar to modulo, but 0 and 9 are taken as 9 """
val = num % modulo
return val if val > 0 else modulo
|
def get_var_id(cloudnet_file_type: str, field: str) -> str:
"""Return identifier for variable / Cloudnet file combination."""
return f"{cloudnet_file_type}-{field}"
|
def merge_sort(lst):
"""Complete a sort based on the merge sort algorithm."""
if len(lst) < 2:
return lst
else:
mid = int(len(lst) // 2)
first_half = lst[:mid]
second_half = lst[mid:]
merge_sort(first_half)
merge_sort(second_half)
i = 0
j = 0
k = 0
while i < len(first_half) and j < len(second_half):
if first_half[i] < second_half[j]:
lst[k] = first_half[i]
i += 1
else:
lst[k] = second_half[j]
j += 1
k += 1
while i < len(first_half):
lst[k] = first_half[i]
i += 1
k += 1
while j < len(second_half):
lst[k] = second_half[j]
j += 1
k += 1
return lst
|
def makeint(number) :
"""Rounds the number"""
rounded = int(round(number))
if rounded > number :
returnval = rounded - 1
else :
returnval = rounded
return returnval
|
def lzip(*args, **kwargs):
"""Take zip generator and make a list for Python 3 work"""
return list(zip(*args, **kwargs))
|
def _compose(args, decs):
"""Helper to apply multiple markers
"""
if len(args) > 0:
f = args[0]
for d in reversed(decs):
f = d(f)
return f
return decs
|
def bool_env(value: bool):
"""
Takes a boolean value(or None) and return the serialized version to be used as an environment variable
Examples:
>>> bool_env(True)
"true"
>>> bool_env(False)
"false"
>>> bool_env(None)
"false"
"""
if value is True:
return "true"
else:
return "false"
|
def imf_kroupa(x):
""" Computes a Kroupa IMF
Keywords
----------
x : numpy vector
masses
Returns
-------
imf : numpy vector
unformalized IMF
"""
m1 = 0.08
m2 = 0.5
alpha0 = -0.3
alpha1 = -1.3
alpha2 = -2.3
if x < m1:
return x**alpha0
elif x >= m2:
return x**alpha2
else:
return x**alpha1
|
def std_trans_map_mdp(sourceidx, action, destidx, p):
"""Standard graphziv attributes used for transitions in mdp.
Computes the attributes for a given source, destination, action and probability.
:param stateidx: The index of the source-state.
:type stateidx: int
:param action: The index of the action.
:type action: int
:param destidx: The index of the destination-state.
:type destidx: int
:param p: probability of the transition.
:type p: float
:rtype: dict"""
return { "color" : "black",
"label" : str(round(p,10)),
"fontsize" : "18pt"}
|
def Multipl_Replace(text, T_replace, new_replace):
"""
:param text: text of interest
:param T_replace: list of element that needed to be replaced in the text
:param new_replace: list of element that we needed to be replaced by.
:return: text after replacing
"""
for item in T_replace:
if item in text:
text = text.replace(item, new_replace)
return text
|
def d2t(dyct):
"""turn the data dictionary into a frozenset
so they are immutable
"""
return tuple(dyct.items())
|
def _ich_in_rxn(ich, spc_dct_i):
""" Check if in a reaction
"""
reacs = spc_dct_i['reacs']
reacs_rev = reacs[::-1]
prods = spc_dct_i['prods']
prods_rev = prods[::-1]
return bool(
list(ich[0]) in (reacs, reacs_rev) and
list(ich[1]) in (prods, prods_rev)
)
|
def A000041(n: int) -> int:
"""Parittion numbers.
a(n) is the number of partitions of n (the partition numbers).
"""
parts = [0] * (n + 1)
parts[0] = 1
for value in range(1, n + 1):
for j in range(value, n + 1):
parts[j] += parts[j - value]
return parts[n]
|
def get_attributes_display_map(obj, attributes):
"""Returns attributes associated with an object,
as dict of Attribute: AttributeValue values.
Args:
attributes: Attribute Iterable
"""
display_map = {}
for attribute in attributes:
value = obj.attributes.get(str(attribute.pk))
if value:
choices = {str(a.pk): a.translated for a in attribute.values.all()}
display_map[attribute.pk] = choices[value]
return display_map
|
def delete_keys_from_dict(dict_del, key):
"""
Method to delete keys from python dict
:param dict_del: Python dictionary with all keys
:param key: key to be deleted in the Python dictionary
:returns a new Python dictionary without the rules deleted
"""
if key in dict_del.keys():
del dict_del[key]
for v in dict_del.values():
if isinstance(v, dict):
delete_keys_from_dict(v, key)
return dict_del
|
def check_status(status):
"""function check_status This function converts a string to a boolean
Args:
status: string of result from compiler
Returns:
boolean
"""
if status == 'success':
return True
return False
|
def proc_avrgs(lst):
"""[summary]
Arguments:
lst {[list]} -- [list of avrg fitness]
Returns:
[list] -- [mult every el by 100 in avrg fitness]
"""
return list(map(lambda x: x * 100, lst))
|
def build_md_table(repos):
"""
Build a reference definition list in markdown syntax, such as:
| Name | Desc |
| :-- | :-- |
| [k3color][] | create colored text on terminal |
| [k3common][] | dependency manager |
"""
res = [
'| Name | Desc |',
'| :-- | :-- |',
]
for repo in repos:
res.append('| [{name}][] | {description} |'.format(**repo))
return '\n'.join(res)
|
def eval_string(value):
"""Evaluate string token"""
return '%s' % value, value
|
def get_param_list(params):
""" transform params from dict to list.
"""
if isinstance(params, dict):
kvList = [(str(k), str(v)) for (k, v) in params.items()]
paramList = [elem for tupl in kvList for elem in tupl]
return paramList
else:
raise ValueError("job params can only be dict")
|
def get_loglevel(level_str):
"""
Get logging level from string.
Empty or incorrect values result in ``INFO`` level.
"""
level_str = level_str.strip().lower()
if level_str == 'notset':
return 0
elif level_str == 'debug':
return 10
elif level_str == 'info':
return 20
elif level_str == 'warning':
return 30
elif level_str == 'critical':
return 50
else:
return 20
|
def prime_factors(n):
"""Returns a dictionary of prime: order. For example 100 (prime factors 2x2x5x5) would return {2: 2, 5:2}"""
if n == 1:
return {}
p = 2
factors = {}
while n >= p * p:
if n % p == 0:
factors.setdefault(p, 0)
factors[p] += 1
n = n / p
else:
if p <= 2:
p += 1
else:
p += 2
n = int(n)
factors.setdefault(n, 0)
factors[n] += 1
return factors
|
def countDecodings(encoded):
"""how many ways can encoded be decoding using mapping"""
#need to split message into all combinations of bigrams and unigrams
if len(encoded) == 1:
return 1
elif len(encoded) == 2:
try:
map[encoded]
if encoded[1] == '0' or encoded[1] == ['1']:
return 1
else:
return 2
except:
return 1
elif len(encoded) == 0:
print(encoded)
return 0
else:
try:
map[encoded[0:2]]
print(encoded)
return countDecodings(encoded[2:]) + countDecodings(encoded[1:])
except:
print(encoded)
return countDecodings(encoded[1:])
|
def is_valid_pdbqt(ext):
""" Checks if is a valid PDB/PDBQT file """
formats = ['pdb', 'pdbqt']
return ext in formats
|
def crear_caja(ncola):
"""Crear caja."""
primer = [[136, 70], 1]
listpos = [primer]
for i in range(1, ncola):
pos = [[listpos[i - 1][0][0] + 150, 70], 1]
listpos.append(pos)
return listpos
|
def improve_email(email):
"""
Given an email string, fix it
"""
import re
exp = re.compile(r'\w+\.*\w+@\w+\.(\w+\.*)*\w+')
s = exp.search(email.lower())
if s is None:
return ""
elif s.group() is not None:
return s.group()
else:
return ""
|
def insert_preext(filename, sub_ext):
"""
Insert a pre-extension before file extension
E.g: 'file.csv' -> 'file.xyz.csv'
"""
fs = filename.split('.')
fs.insert(-1, sub_ext)
fn = '.'.join(fs)
return fn
|
def reverse_vertices(vertices):
"""Reverse vertices. Useful to reorient the normal of the polygon."""
reversed_vertices = []
nv = len(vertices)
for i in range(nv-1, -1, -1):
reversed_vertices.append(vertices[i])
return reversed_vertices
|
def partition(array, low, high):
"""This function implements the partition entity.
Partition works this way:
it reorders the sub-array of elements less that the pivot to
come before it,
and reorders the sub-array of elements whose values are greater than
the pivot to come after it.
"""
pivot = array[low]
i = low + 1
j = high
done = False
while not done:
while i <= j and array[i] <= pivot:
i += 1
while array[j] >= pivot and j >= i:
j -= 1
if i >= j:
done = True
else:
# swap array[i] with array[j]
temp = array[i]
array[i] = array[j]
array[j] = temp
temp = array[low]
array[low] = array[j]
array[j] = temp
return j
|
def valuecallable(obj):
"""
Intenta invocar el objeto --> obj() y retorna su valor.
"""
try:
return obj()
except (TypeError):
return obj
|
def unquote_string(s):
"""Remove single and double quotes from beginning and end of `s`."""
if isinstance(s, bytes):
s = s.decode()
if not isinstance(s, str):
s = str(s)
for quote in ("'", '"'):
s = s.rstrip(quote).lstrip(quote)
return s
|
def siteswapTest(site):
"""takes in siteswap array, returns the throw-based validity of the pattern"""
siteLen = len(site)
valid = True
corrCatches = [0] * siteLen #how many should land in each index
actualCatches = [0] * siteLen #how many actually land in each index
for i in range(0, siteLen): #this loop builds corrCatches array
if isinstance(site[i], list):
corrCatches[i] = len(site[i]) #amt of lands = amt of throws
else:
corrCatches[i] = 1 #this is even for 0 case since "throw" lands in same spot
for i in range(0, siteLen): #this loop builds actualCatches array
#add a 1 to index where the ball thrown lands
if isinstance(site[i], list):
for j in range(0, len(site[i])):
actualCatches[(i + site[i][j]) % siteLen] += 1
else:
actualCatches[(i + site[i]) % siteLen] += 1
for i in range(1, siteLen): #this loop compares corrCatches and actualCatches
if valid:
valid = corrCatches[i] == actualCatches[i]
return valid
|
def _dos_order(key):
"""
Key function for sorting DOS entries in predictable order:
1. Energy Grid
2. General keys (Total, interstitial, ...)
3. Atom contribution (total, orbital resolved)
"""
if key == 'energy_grid':
return (-1,)
if '_up' in key:
key = key.split('_up')[0]
spin = 0
else:
key = key.split('_down')[0]
spin = 1
general = ('Total', 'INT', 'Sym')
orbital_order = ('', 's', 'p', 'd', 'f')
if key in general:
return (spin, general.index(key))
if ':' in key:
before, after = key.split(':', maxsplit=1)
tail = after.lstrip('0123456789')
index = int(after[:-len(tail)]) if len(tail) > 0 else int(after)
tail = tail.lstrip(',')
if tail.startswith('ind:'):
tail = int(tail[4:])
if tail in orbital_order:
return (spin, len(general) + index, orbital_order.index(tail), '')
if isinstance(tail, int):
return (spin, len(general) + index, tail, '')
return (spin, len(general) + index, float('inf'), tail)
return None
|
def populate_documents(query, dictree, docpath):
"""
populates documents in an existing dictree for the shelters it contains
"""
for d in query:
if d.shelter_id in dictree:
if not dictree[d.shelter_id][d.name]["Documents"]:
dictree[d.shelter_id][d.name]["Documents"] = [
"{}/{}/{}".format(docpath, d.shelter_id, d.filename)
]
else:
dictree[d.shelter_id][d.name]["Documents"].append(
"{}/{}/{}".format(docpath, d.shelter_id, d.filename)
)
return dictree
|
def safe_div(a, b):
"""
returns a / b, unless b is zero, in which case returns 0
this is primarily for usage in cases where b might be systemtically zero, eg because comms are disabled or similar
"""
return 0 if b == 0 else a / b
|
def parse_pdf_to_string(pdf_file_path):
"""
:param pdf_file_path: file path of a pdf to convert into a string
:return: string of the parsed pdf
"""
pdf_string = ''
return pdf_string
|
def make_choices(choices):
"""
Zips a list with itself for field choices.
"""
return list(zip(choices, choices))
|
def correct_point(obj):
"""
Function to check if object can be used as point coordinates in 3D Decart's system
:param obj: object to check
:return: True or False
"""
check = tuple(obj)
if len(check) == 3 and all([isinstance(item, (int, float)) for item in check]):
return True
else:
return False
|
def patch_prow_job_with_group(prow_yaml, test_group, force_group_creation=False):
"""Updates a prow YAML object
Assumes a valid prow yaml and a compatible test group
Will amend existing annotations or create one if there is data to migrate
If there is no migratable data, an annotation will be forced only if specified
"""
if "annotations" in prow_yaml:
# There exists an annotation; amend it
annotation = prow_yaml["annotations"]
else:
annotation = {}
# migrate info
opt_arguments = [("num_failures_to_alert", "testgrid-num-failures-to-alert"),
("alert_stale_results_hours", "testgrid-alert-stale-results-hours"),
("num_columns_recent", "testgrid-num-columns-recent")]
for group_arg, annotation_arg in opt_arguments:
if (group_arg in test_group and annotation_arg not in annotation):
# Numeric arguments need to be coerced into strings to be parsed correctly
annotation[annotation_arg] = str(test_group[group_arg])
if force_group_creation and "testgrid-dashboards" not in annotation:
annotation["testgrid-create-test-group"] = "true"
if not any(annotation):
return prow_yaml
prow_yaml["annotations"] = annotation
return prow_yaml
|
def gaussian_gradient(x: float, mean: float, var: float) -> float:
"""Analytically evaluate Gaussian gradient."""
gradient = (mean - x) / (var ** 2)
return gradient
|
def getCoOccurrenceMatrix(image, d):
"""
Calculates the co-occurrence matrix of an image.
@param image: the image to calculate the co-occurrence matrix for
@param d: the distance to consider
@return: the co-occurrence matrix
"""
dr = d[0]
dc = d[1]
# get the image dimensions
rows = len(image)
cols = len(image[0])
# create the co-occurrence matrix
coOccurrenceMatrix = {}
for row in range(rows - dr):
for col in range(cols - dc):
pixel = image[row][col]
offsetPixel = image[row + dr][col + dc]
if (pixel, offsetPixel) not in coOccurrenceMatrix:
coOccurrenceMatrix[(pixel, offsetPixel)] = 1
else:
coOccurrenceMatrix[(pixel, offsetPixel)] += 1
return coOccurrenceMatrix
|
def add_signals(sig1: list, sig2: list):
"""
Sums two signal lists together
:param sig1: signal 1
:param sig2: signal 2
:return: new summed signal
"""
if len(sig1) != len(sig2):
return None
return [s1 + s2 for s1, s2 in zip(sig1, sig2)]
|
def lambdas_naive(sequence):
"""
Compute the lambdas in the following equation:
Equation:
S_{real} = \left( \frac{1}{n} \sum \Lambda_{i} \right)^{-1}\log_{2}(n)
Args:
sequence: the input sequence of symbols.
Returns:
The sum of the average length of sub-sequences that
(up to a certain point) do not appear in the original sequence.
Reference:
Kontoyiannis, I., Algoet, P. H., Suhov, Y. M., & Wyner, A. J. (1998).
Nonparametric entropy estimation for stationary processes and random
fields, with applications to English text. IEEE Transactions on Information
Theory, 44(3), 1319-1327.
"""
lambdas = 0
for i in range(len(sequence)):
current_sequence = ','.join(sequence[0:i])
match = True
k = i
while match and k < len(sequence):
k += 1
match = ','.join(sequence[i:k]) in current_sequence
lambdas += (k - i)
if lambdas==0:
lambdas=1
return lambdas
|
def expandtabs(s, tabsize=8):
"""expandtabs(s [,tabsize]) -> string
Return a copy of the string s with all tab characters replaced
by the appropriate number of spaces, depending on the current
column, and the tabsize (default 8).
"""
return s.expandtabs(tabsize)
|
def str_to_bool(bool_str):
"""Convert string to bool. Usually used from argparse. Raise error if don't know what value.
Possible values for True: 'yes', 'true', 't', 'y', '1'
Possible values for False: 'no', 'false', 'f', 'n', '0'
Args:
bool_str (str):
Raises:
TypeError: If not one of bool values inferred, error is raised.
Returns:
bool: True or False
Example:
>>> str_to_bool("y")
True
Argparse example::
parser = argparse.ArgumentParser()
parser.add_argument(
"--test",
choices=(True, False),
type=str_to_bool,
nargs="?",
)
"""
if isinstance(bool_str, bool):
return bool_str
if bool_str.lower() in ("yes", "true", "t", "y", "1"):
return True
elif bool_str.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise TypeError("Boolean value expected.")
|
def to_hex(color):
"""
Color utility, converts a whitespace separated triple of
numbers into a hex code color.
"""
if not color[0] == '#':
rgb = tuple(map(int, color.split(' ')))
color = '#%02x%02x%02x' % rgb
return color
|
def make_modifier_scale(scale):
"""Make a string designating a scaling transformation, typically for
filenames of rescaled images.
Args:
scale (float): Scale to which the image was rescaled. Any decimal
point will be replaced with "pt" to avoid confusion with
path extensions.
Returns:
str: String designating the scaling transformation.
"""
mod = "scale{}".format(scale)
return mod.replace(".", "pt")
|
def to_base(num, b, numerals='0123456789abcdefghijklmnopqrstuvwxyz'):
"""
Python implementation of number.toString(radix)
Thanks to jellyfishtree from https://stackoverflow.com/a/2267428
"""
return ((num == 0) and numerals[0]) or (to_base(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
|
def _create_rects(rect_list):
"""
Create a vertex buffer for a set of rectangles.
"""
v2f = []
for shape in rect_list:
v2f.extend([-shape.width / 2, -shape.height / 2,
shape.width / 2, -shape.height / 2,
shape.width / 2, shape.height / 2,
-shape.width / 2, shape.height / 2])
return v2f
|
def str_to_ascii_lower_case(s):
"""Converts the ASCII characters in the given string to lower case."""
return ''.join([c.lower() if 'A' <= c <= 'Z' else c for c in s])
|
def get_id(record):
"""
Returns the Amazon DynamoDB key.
"""
return record['dynamodb']['Keys']['id']['S']
|
def intersect(a, b):
"""Return the intersection of two lists.
"""
return list(set(a) & set(b))
|
def normalized_in_degree(in_degree_dict):
"""dict -> dict
Takes a dictionary of nodes with their indegree value, and returns a
normalized dictionary whose values sum up to 1.
"""
normalized = {}
for key in in_degree_dict:
normalized[key] = float(in_degree_dict[key]) / len(in_degree_dict)
return normalized
|
def build_template(cfg: dict) -> dict:
"""
Build string's template dictionary
:rtype: dict
:param cfg: representation of the config
:return: dictionary to be used with Template().substutute() function
"""
task = cfg['main']
def concat(*dictionaries: dict) -> dict:
res = dict()
for d in dictionaries:
res = {**res, **d}
return res
template = concat(task['miner'], task['pool'], cfg['rig'])
return template
|
def lookup(dictionary, key):
"""
Helpers tag to lookup for an entry inside of a dictionary, ruturns `None`
for nonexisting keys.
"""
return dictionary.get(key.lower())
|
def name_reverse(name):
"""Switch family name and given name"""
fam, giv = name.split(',', 1)
giv = giv.strip()
return giv + ', ' + fam
|
def dio(average_inventory_cost, cost_of_goods_sold):
"""Return the DIO or Days of Inventory Outstanding over the previous 365 days.
Args:
average_inventory_cost (float): Average cost of inventory.
cost_of_goods_sold (float): Cost of goods sold.
Returns:
Days of Inventory Outstanding (float).
"""
return (average_inventory_cost / cost_of_goods_sold) * 365
|
def is_float(in_value):
"""Checks if a value is a valid float.
Parameters
----------
in_value
A variable of any type that we want to check is a float.
Returns
-------
bool
True/False depending on whether it was a float.
Examples
--------
>>> is_float(1.5)
True
>>> is_float(1)
False
"""
try:
return not float(in_value).is_integer()
except (ValueError, TypeError):
return False
|
def is_overlap(var_pos, intervals):
"""Overlap a position with a set of intervals"""
for s, e in intervals:
if s<=var_pos<=e: return True
return False
|
def make_float(value):
"""Makes an float value lambda."""
return float(value[0])
|
def _get_func(module, func_name):
"""
Given a module and a function name, return the function.
func_name can be of the forms:
- 'foo': return a function
- 'Class.foo': return a method
"""
cls_name = None
cls = None
if '.' in func_name:
cls_name, func_name = func_name.split('.')
if cls_name:
cls = getattr(module, cls_name)
func = getattr(cls, func_name)
else:
func = getattr(module, func_name)
return cls, func
|
def delete_name(L, name, delete_following = False):
"""
Remove all occurrences of name from any ballot in L.
When used to remove undervotes, make sure double undervotes
have already been handled (since following votes are then
also eliminated).
Args:
L (list): list of ballots
name (str): name of choice to be eliminated
delete_following (bool): True if all following positions on ballot
are also to be eliminated
Returns:
(list): list of possibly modified ballots
Examples:
>>> L = [('a', 'undervote', 'b'), ('undervote',), ('c',), ()]
>>> delete_name(L, 'undervote')
[('a', 'b'), (), ('c',), ()]
"""
LL = []
for ballot in L:
if name in ballot:
new_ballot = []
for c in ballot:
if c != name:
new_ballot.append(c)
elif delete_following:
break
else:
new_ballot = ballot
LL.append(tuple(new_ballot))
return LL
|
def get_base_target_link(experiment_config):
"""Returns the base of the target link for this experiment so that
get_instance_from_preempted_operation can return the instance."""
return ('https://www.googleapis.com/compute/v1/projects/{project}/zones/'
'{zone}/instances/').format(
project=experiment_config['cloud_project'],
zone=experiment_config['cloud_compute_zone'])
|
def truncate(message, from_start, from_end=None):
"""
Truncate the string *message* until at max *from_start* characters and
insert an ellipsis (`...`) in place of the additional content. If *from_end*
is specified, the same will be applied to the end of the string.
"""
if len(message) <= (from_start + (from_end or 0) + 3):
return message
part1, part2 = message[:from_start], ''
if from_end and len(message) > from_end:
if len(message) - from_start < from_end:
from_end -= len(message) - from_start
part2 = message[-from_end:]
return part1 + '...' + part2
|
def _get_keywords_from_textmate(textmate):
"""Return keywords from textmate object.
"""
return [
kw["match"] for kw in textmate["repository"]["language_keyword"]["patterns"]
]
|
def u4u1(u4):
"""
pixel pitch -> mm
u4 = (pitch, pixel)
"""
u1 = round( u4[0] * u4[1], 2)
return u1
|
def counting_sort(array):
"""
Counting Sort
Complexity: O(N + K)
Imagine if array = [1, 100000].
Then, N = 2 and K = 100000, K >> N^2.
And thus, it far exceeds the O(N^2) complexity.
That's why O(N + K) is deceptive.
"""
max_value = max(array)
temp = [0] * max_value
for i in range(len(array)):
temp[array[i]-1] += 1
sorted_array = []
for i in range(max_value):
if temp[i] == 0:
continue
k = temp[i]
value = i + 1
while k:
sorted_array.append(value)
k -= 1
return sorted_array
|
def str_replace_all(x, replacements):
""" Dictionary replacements
Description
-----------
Replaces strings found in dictionary. The replacement is made in the order
in which the replacements in the dictionary are provided. This opens up
opportunities for patterns created after serial replacement to be detected
and replaced again.
Parameters
----------
x : string
The text to replace
replacements : dictionary
The dictionary of items to replace
Returns
-------
The same string passed with the text found substituted.
Reference
---------
https://stackoverflow.com/a/6117042
Warnings
--------
Python dictionaries don't have a reliable order for iteration. This solution
only solves your problem if:
* order of replacements is irrelevant
* it's ok for a replacement to change the results of previous replacements
Inefficient if `text` is too big or there are many pairs in the dictionary.
Example
-------
x = "The quick brown fox"
d = {'brown': 'green', 'quick': 'slow', 'fox': 'platypus'}
str_replace_all(x, d)
"""
from collections import OrderedDict
replacements = OrderedDict(replacements)
for i, j in replacements.items():
x = x.replace(i, j)
return x
|
def add_jekyll_header(html_str, layout, title, description):
"""
Add the Jekyll header to the html strings.
Args:
html_str (str): HTML of converted notebook.
layout (str): Jekyll layout to use.
title (str): Title to use.
description (str): Description to use
Returns:
(str): HTML with Jekyll layout header on top.
"""
header = '\n'.join([
'---',
'layout: {}'.format(layout),
'title: {}'.format(title),
'description: {}'.format(description),
'---',
''
])
return '\n'.join([header, html_str])
|
def regularize_ontology_id(value):
"""Regularize ontology_ids for storage with underscore format
"""
try:
return value.replace(":", "_")
except AttributeError:
# when expected value is not actually an ontology ID
# return the bad value for JSON schema validation
return value
|
def extension(filename):
""" returns the extension when given a filename
will return None if there is no extension
>>> extension('foo.bar')
'bar'
>>> extension('foo')
None
"""
s = filename.split('.')
if len(s) > 1:
return s[-1]
else:
return None
|
def determine_length(data):
"""
determine message length from first bytes
:param data: websocket frame
:return:
"""
byte_array = [d for d in data[:10]]
data_length = byte_array[1] & 127
if data_length == 126:
data_length = (byte_array[2] & 255) * 2**8
data_length += byte_array[3] & 255
elif data_length == 127:
data_length = (byte_array[2] & 255) * 2**56
data_length += (byte_array[3] & 255) * 2**48
data_length += (byte_array[4] & 255) * 2**40
data_length += (byte_array[5] & 255) * 2**32
data_length += (byte_array[6] & 255) * 2**24
data_length += (byte_array[7] & 255) * 2**16
data_length += (byte_array[8] & 255) * 2**8
data_length += byte_array[9] & 255
return data_length
|
def parse_entry_tags(entry):
"""Return a list of tag objects of the entry"""
tags = set()
for tag in entry.get('tags', []):
term = tag.get('label') or tag.get('term') or ''
for item in term.split(','):
item = item.strip().lower()
if item:
tags.add(item)
return list(tags)
|
def get_file_size_string(size):
"""
returns the size in kbs
"""
size_in_kb = "{0:.3f}".format(size/1000.0)
return str(size_in_kb) + " kb"
|
def sanitize_model_dict(obj):
"""Sanitize zeep output dict with `_value_N` references.
This is useful for data processing where one wishes to consume the 'get' api data instead of re-purposing
it in e.g. an 'update' api call. Achieved by flattening the nested OrderedDict by replacing
the nested dict for AXL's 'XFkType' with the value specified in zeep's `_value_N` key.
Note: Doing so disregards 'uuid' values.
Example:
sample_model_dict = {
'name': 'SEPAAAABBBBCCCC',
'callingSearchSpaceName': {
'_value_1': 'US_NYC_NATIONAL_CSS',
'uuid': '{987345984385093485gd09df8g}'
}
}
is sanitized to:
sanitized_sample_model_dict = {
'name': 'SEPAAAABBBBCCCC',
'callingSearchSpaceName': 'US_NYC_NATIONAL_CSS'
}
:param obj: (dict) AXL data model
:return: sanitized AXL data model
"""
if set(obj.keys()) == {"uuid", "_value_1"} or set(obj.keys()) == {"_value_1"}:
return obj["_value_1"]
else:
for k, v in obj.items():
if isinstance(v, dict):
obj[k] = sanitize_model_dict(v)
elif isinstance(v, list):
obj[k] = [sanitize_model_dict(item) for item in v]
return obj
|
def decide_winner(player1Choice, player2Choice):
"""Decides who wins the round.
Assumes that inputs are either 'Rock', 'Paper', 'Scissors'"""
if player1Choice == player2Choice:
return "It's a Tie"
if player1Choice == "Rock":
if player2Choice == "Scissors":
return "Player 1"
elif player2Choice == "Paper":
return "Player 2"
elif player1Choice == "Paper":
if player2Choice == "Rock":
return "Player 1"
elif player2Choice == "Scissors":
return "Player 2"
elif player1Choice == "Scissors":
if player2Choice == "Paper":
return "Player 1"
elif player2Choice == "Rock":
return "Player 2"
|
def _overlapping_genes(genes, gs_genes):
"""
Returns overlapping genes in a gene set
"""
return list(set.intersection(set(genes), gs_genes))
|
def _merge_dict(source, destination):
"""Recursive dict merge"""
for key, value in source.items():
if isinstance(value, dict):
node = destination.setdefault(key, {})
_merge_dict(value, node)
else:
destination[key] = value
return destination
|
def normalize_segmentation(seg):
"""
Bring the segmentation into order.
Parameters
----------
seg : list of lists of ints
Returns
-------
seg : list of lists of ints
Examples
--------
>>> normalize_segmentation([[5, 2], [1, 4, 3]])
[[1, 3, 4], [2, 5]]
"""
return sorted(sorted(el) for el in seg)
|
def get_account_deploy_count(accounts: int, account_idx: int, deploys: int) -> int:
"""Returns account index to use for a particular transfer.
"""
if accounts == 0:
return 1
q, r = divmod(deploys, accounts)
return q + (1 if account_idx <= r else 0)
|
def is_palindrome_v5(string):
"""palindrome recursive version"""
if len(string) <= 1:
return True
if string[0] != string[-1]:
return False
else:
return is_palindrome_v5(string[1:-1])
|
def _recursive_dict_keys(a_dict):
"""Find all keys of a nested dictionary"""
keys = set(a_dict.keys())
for _k, v in a_dict.items():
if isinstance(v, dict):
keys.update(_recursive_dict_keys(v))
return keys
|
def FlagIsHidden(flag_dict):
"""Returns whether a flag is hidden or not.
Args:
flag_dict: a specific flag's dictionary as found in the gcloud_tree
Returns:
True if the flag's hidden, False otherwise or if flag_dict doesn't contain
the 'hidden' key.
"""
return flag_dict.get('hidden', False)
|
def matrix_divided(matrix, div):
"""
Devides all elements in matrix
Args:
matrix (list[list[int/float]]) : matrice
div (int/float) Devider
Raise:
TypeError: div not int or float
TypeError: matix is not a list of list of number
ZeroDivisionError: Div is 0
Return : New matrix Devided
"""
if type(div) not in [int, float]:
raise TypeError("div must be a number")
if div == 0:
raise ZeroDivisionError('division by zero')
if type(matrix) is not list or not all((type(l) is list)for l in matrix) \
or not all((isinstance(n, (int, float))for n in l)for l in matrix) \
or len(matrix[0]) == 0:
raise TypeError(
"matrix must be a matrix "
"(list of lists) of integers/floats")
l = len(matrix[0])
if not all((len(x) == l)for x in matrix):
raise TypeError("Each row of the matrix must have the same size")
return [list(map(lambda x: round(x / div, 2), r))for r in matrix]
|
def find_rlc(p_utility, q_utility, r_set, l_set, c_set):
"""
Proportional controllers for adjusting the resistance and capacitance values in the RLC load bank
:param p_utility: utility/source active power in watts
:param q_utility: utility/source reactive power in var
:param r_set: prior resistor % change
:param l_set: prior inductor % change
:param c_set: prior capacitor % change
:return:
"""
smoothing_factor = 0.50 # only move a small percentage of the desired change for stability
cap = c_set + (6./1300. * q_utility) * smoothing_factor
res = r_set + (50.5/11700. * p_utility) * smoothing_factor
return res, l_set, cap
|
def get_unaligned_regions(seq_i, seq_j, minimum_len=4):
"""
Return the ungapped regions in `seq_j` that do not align with `seq_i`.
Returned regions should have at least `minimum_len`.
>>> seq_i = '------MHKCLVDE------YTEDQGGFRK------'
>>> seq_j = 'MLLHYHHHKC-------LMCYTRDLHG---IH-L-K'
>>> get_unaligned_regions(seq_i, seq_j)
['MLLHYH', 'IHLK']
>>> seq_i = 'XXXXXXXXXXMHKCLVDE------YTEDQGGFRK'
>>> seq_j = '----MLLHYHHHKC-------LMCYTRDLHG---'
>>> get_unaligned_regions(seq_i, seq_j)
['MLLHYH']
>>> seq_i = 'XXXXXXXXXXMHKCLVDE------YTEDQGGFRK'
>>> seq_j = '----MLLHYHHHKC-----XXLMCYTRDLHG---'
>>> get_unaligned_regions(seq_i, seq_j)
['MLLHYH', 'XXLMC']
"""
j_sequences = []
j_region = []
in_region = False
for (res_i, res_j) in zip(seq_i, seq_j):
if res_i in {'-', 'X'}:
in_region = True
if res_j != '-':
j_region.append(res_j)
elif in_region:
seq = ''.join(j_region)
j_region.clear()
in_region = False
if len(seq) >= minimum_len:
j_sequences.append(seq)
seq = ''.join(j_region)
if len(seq) >= minimum_len:
j_sequences.append(seq)
return j_sequences
|
def ambientT(y, Q=0, T0 = 20):
"""
y - in mmm
output in degC
"""
return T0 + y * (3/100)
|
def cognito_pool_url(aws_pool_region, cognito_pool_id):
""" Function to create the AWS cognito issuer URL for the user pool using
the pool id and the region the pool was created in.
Returns: The cognito pool url
"""
return ("https://cognito-idp.{}.amazonaws.com/{}".format(
aws_pool_region, cognito_pool_id))
|
def _LocationScopeType(instance_group):
"""Returns a location scope type, could be region or zone."""
if 'zone' in instance_group:
return 'zone'
elif 'region' in instance_group:
return 'region'
else:
return None
|
def score(value, mu, musquared):
"""
Helper function for use in assigning negative prizes (when mu > 0)
"""
if mu <= 0:
raise ValueError("User variable mu is not greater than zero.")
if value == 1:
return 0
else:
newvalue = -float(value) # -math.log(float(value),2)
if musquared:
newvalue = -(newvalue * newvalue)
newvalue = newvalue * mu
return newvalue
|
def bytes_value_provider(value, gettext):
"""Converts ``value`` to ``bytes``."""
if value is None:
return None
t = type(value)
if t is bytes:
return value
if t is str:
return value.encode("UTF-8")
return str(value).encode("UTF-8")
|
def move_exists(b):
"""
Check whether or not a move exists on the board
Args: b (list) two dimensional board to merge
Returns: list
>>> b = [[1, 2, 3, 4], [5, 6, 7, 8]]
>>> move_exists(b)
False
>>> move_exists(test)
True
"""
for row in b:
for x, y in zip(row[:-1], row[1:]):
if x == y or x == 0 or y == 0:
return True
return False
|
def _above_threshold(flatstat, threshold):
"""Returns true of the CC of flatstat is
equal to or above self.threshold."""
return flatstat[2] >= threshold
|
def _format_mark(mark_input: str) -> float:
""" Format the mark into the correct format. The mark is in the form x%,
where x / 100 <= 1.
:param: mark_input: the input of the user
:return: the value of the mark.
"""
evaluated_mark = eval(mark_input)
if evaluated_mark <= 1:
return round(evaluated_mark * 100, 2)
else:
return evaluated_mark
|
def swap(l, i, j):
"""
Swap the index i with the index j in list l.
Args:
l (list): list to perform the operation on.
i (int): left side index to swap.
j (int): Right side index to swap.
Returns:
list
"""
l[i], l[j] = l[j], l[i]
return l
|
def delete_nth(order, max_e):
"""create a new list that contains each number of
lst at most N times without reordering.
"""
answer_dict = {}
answer_list = []
for number in order:
if number not in answer_dict:
answer_dict[number] = 1
else:
answer_dict[number] += 1
if answer_dict[number] <= max_e:
answer_list.append(number)
return answer_list
|
def validate_target(header_hash, bits):
"""Validate PoW target"""
target = ('%064x' % ((bits & 0xffffff) * (1 << (8 * ((bits >> 24) - 3))))).split('f')[0]
zeros = len(target)
return header_hash[::-1].hex()[:zeros] == target
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.