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'] ... |
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... |
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:
... |
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... |
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 acti... |
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:
... |
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))
... |
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():
de... |
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][]... |
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 onl... |
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 2... |
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 ... |
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... |
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.
... |
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):... |
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.... |
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"] ... |
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
els... |
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 on... |
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... |
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 ... |
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 on... |
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 extens... |
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,
... |
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... |
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()
... |
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 Outstandin... |
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)
T... |
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... |
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
... |
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(
... |
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 + (fr... |
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
... |
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 repl... |
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:
... |
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 va... |
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 == ... |
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(it... |
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 fo... |
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 "Playe... |
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]]
"""
retur... |
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
ZeroD... |
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 %... |
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_... |
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, ... |
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)
... |
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... |
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 rou... |
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... |
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.