content stringlengths 42 6.51k |
|---|
def chao1_var_uncorrected(singles, doubles):
"""Calculates chao1, uncorrected.
From EstimateS manual, equation 5.
"""
r = float(singles)/doubles
return doubles*(.5*r**2 + r**3 + .24*r**4) |
def nth_triangle(n):
"""
Compute the nth triangle number
"""
return n * (n + 1) // 2 |
def extract_defs(text):
"""The site formats its definitions as list items <LI>definition</LI>
We first look for all of the list items and then strip them of any... |
def unique_list(a_list):
""" Creates an ordered list from a list of tuples or other hashable items.
From https://code.activestate.com/recipes/576694/#c6
"""
m_map = {}
o_set = []
for item in a_list:
if item not in m_map:
m_map[item] = 1
o_set.append(item)
retu... |
def integerToRoman(num: int) -> str:
"""Return roman numeral for an integer."""
# William Chapman, Jorj McKie, 2021-01-06
roman = (
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, ... |
def ioc_match(indicators: list, known_iocs: set) -> list:
"""Matches a set of indicators against known Indicators of Compromise
:param indicators: List of potential indicators of compromise
:param known_iocs: Set of known indicators of compromise
:return: List of any indicator matches
"""
# Che... |
def get_anyone_answers(response: str) -> int:
"""
Iterate over input string and append to list when char
not in string.
:return: Count of positive answers
:rtype: int
"""
questions = []
for char in response:
if char not in questions:
questions.append(char)
return... |
def trace(a):
"""
Returns the race of matrix 'a'.
:param a: The matrix.
:return: The trace of the matrix
"""
result = 0
for index in range(len(a)):
try:
result += a[index][index]
except:
return result
return result |
def myfun(param):
"""Function documentation"""
c = 2 + param
return c |
def create_demag_params(atol, rtol, maxiter):
"""
Helper function to create a dictionary with the given
demag tolerances and maximum iterations. This can be
directly passed to the Demag class in order to set
these parameters.
"""
demag_params = {
'absolute_tolerance': atol,
'... |
def teleport_counts(shots, hex_counts=True):
"""Reference counts for teleport circuits"""
targets = []
if hex_counts:
# Classical 3-qubit teleport
targets.append({'0x0': shots / 4, '0x1': shots / 4,
'0x2': shots / 4, '0x3': shots / 4})
else:
# Classical 3-... |
def unpack_bits( byte ):
"""Expand a bitfield into a 64-bit int (8 bool bytes)."""
longbits = byte & (0x00000000000000ff)
longbits = (longbits | (longbits<<28)) & (0x0000000f0000000f)
longbits = (longbits | (longbits<<14)) & (0x0003000300030003)
longbits = (longbits | (longbits<<7)) & (0x01010101010... |
def calc_kappa1(T_K):
"""
Calculates kappa1 in the PWP equation.
Calculates kappa1 in the PWP equation, according to Equation 5 in Plummer, Wigley, and Parkhurst (1978) or Equation 6.13 of Dreybrodt (1988).
Parameters
----------
T_K : float
temperature Kelvin
Returns
-------
... |
def _WrapWithGoogScope(script):
"""Wraps source code in a goog.scope statement."""
return 'goog.scope(function() {\n' + script + '\n});' |
def caculate_matmul_shape(matrix_A_dim, matrix_G_dim, split_dim):
"""get matmul shape"""
split_dimA = split_dim
split_dimG = split_dim
if matrix_A_dim % split_dim == 0:
batch_w = matrix_A_dim // split_dim
else:
if matrix_A_dim < split_dim:
batch_w = 1
split_di... |
def parse_cookie(data):
"""
Parses/interprets the provided cookie data string, returning a
map structure containing key to value associations of the various
parts of the cookie.
In case no key value association exists for the cookie the value
for such cookie (key) is stored and an empty ... |
def mutate_dict(
inValue,
keyFn=lambda k: k,
valueFn=lambda v: v,
keyTypes=None,
valueTypes=None,
**kwargs
):
"""
Takes an input dict or list-of-dicts and applies ``keyfn`` function to all of the keys in
both the top-level and any nested dicts or lists, and ``valuefn`` to all
If ... |
def _key_in_string(string, string_formatting_dict):
"""Checks which formatting keys are present in a given string"""
key_in_string = False
if isinstance(string, str):
for key, value in string_formatting_dict.items():
if "{" + key + "}" in string:
key_in_string = True
... |
def jaccard(set1, set2):
"""
computes the jaccard coefficient between two sets
@param set1: first set
@param set2: second set
@return: the jaccard coefficient
"""
if len(set1) == 0 or len(set2) == 0:
return 0
inter = len(set1.intersection(set2))
return inter / (len(set1) + le... |
def calc_boost_factor(pokemon, stat_name):
"""
Calculate the multiplicative modifier for a pokemon's stat.
Args:
pokemon (Pokemon): The pokemon for whom we are calculating.
stat (str): The stat for which we are calculating this for.
Returns:
The multiplier to apply to that poke... |
def str2list(string):
"""Convert a string with comma separated elements to a python list.
Parameters
----------
string: str
A string with comma with comma separated elements
Returns
-------
list
A list.
"""
string_list = [str_.rstrip(" ").lstrip(" ") for str_ in str... |
def make_comp(terms, joiner='OR'):
"""Make a search term component.
Parameters
----------
terms : list of str
List of words to connect together with 'OR'.
joiner : {'OR', AND', 'NOT'}
The string to join together the inputs with.
Returns
-------
comp : str
Search... |
def iterMandel(x, y, iterMax):
"""
Dadas las partes real e imaginaria de un numero complejo,
determina la iteracion en la cual el candidato al conjunto
de Mandelbrot se escapa.
"""
c = complex(x, y)
z = 0.0j
for i in range(iterMax):
z = z**2 + c
if abs(z) >= 2:
... |
def get_last_update_id(updates):
"""
Calculates the highest ID of all the updates it receive from getUpdates.
:param updates: getUpdates()
:return: last update id
"""
update_ids = []
for update in updates["result"]:
update_ids.append(int(update["update_id"]))
return max(update_id... |
def prepare(data):
"""Restructure/prepare data about refs for output."""
ref = data.get("ref")
obj = data.get("object")
sha = obj.get("sha")
return {"ref": ref, "head": {"sha": sha}} |
def committee_to_json(req_data):
"""
Simply convert the request object into JSON
without filtering the data.
"""
if req_data is None or len(req_data) == 0:
return None
result = []
for item in req_data:
result.append(item.json_data())
return result |
def _clean_page_wheel(text):
"""
remove unexpected characters
@param text string
@return string
"""
text = text.replace(""", "'")
text = text.replace("‑", "-")
text = text.replace(".", ".")
text = text.replace(" · ", "-")
text = ... |
def string_transformer(s: str) -> str:
"""
Given a string, return a new string that has
transformed based on the input:
1. Change case of every character, ie. lower
case to upper case, upper case to lower case.
2. Reverse the order of words from the input.
Note: You will have to handle multiple spaces, and
... |
def format_percentage(number):
"""
Formats a number into a percentage string
:param number: a number assumed to be between 0 and 1
:return: str
"""
return '{}%'.format(round(number * 100)) |
def lists_are_same(L1, L2):
"""compare two lists"""
return len(L1) == len(L2) and sorted(L1) == sorted(L2) |
def get_node(i,nodes):
"""
Helper function for checking the list of nodes for a specif node and returning it.
Parameters:
-----------
i: int
The number of the node to search the given list
nodes: list of Node
The list of nodes to be searched
Returns:
... |
def discretize_yaw(yaw):
"""
Discretize a yaw angle into the 4 canonical yaw angles/directions
"""
# normalize to [0, 360]
if yaw < 0:
yaw_normalized = 360 + yaw
else:
yaw_normalized = yaw
# discretize
if (yaw_normalized >= 270 + 45 and yaw_normalized <= 360) or (yaw_normalized >= 0 and yaw_normalized < 0... |
def ChangeNegToDash(val):
"""Helper function for a map call"""
if val == -1.0:
return '-'
return val |
def _to_dict(param_list):
"""Convert a list of key=value to dict[key]=value"""
if param_list:
return {
name: value for (
name,
value) in [
param.split('=') for param in param_list]}
else:
return None |
def str_to_bool(param):
"""Check if a string value should be evaluated as True or False."""
if isinstance(param, bool):
return param
return param.lower() in ("true", "yes", "1") |
def _is_line_ends_with_message(line: str) -> bool:
"""
Helper, checks if an assert statement ends with a message.
:param line: assert statement text to check for a message
:return: True if message exists, False otherwise
"""
line = line[::-1].replace(' ', '')
if line[0] != "'" and line[0] !... |
def last_third_first_third_mid_third(seq):
"""with the last third, then first third, then the middle third in the new order."""
i = len(seq) // 3
return seq[-i:] + seq[:i] + seq[i:-i] |
def pack_ushort_to_hn(val):
"""
Pack unsigned short to network order unsigned short
"""
return ((val & 0xff) << 8) | ((val & 0xff00) >> 8) & 0xffff |
def validate_hcl(value: str) -> bool:
"""Value must be an HTML color string"""
if not value.startswith("#") or len(value) != 7:
return False
try:
# remainder must be a valid hex string
int(value[1:], 16)
except ValueError:
return False
else:
return True |
def walk_tree(root, *node_types):
"""
Return a list of nodes (optionally filtered by type) ordered by the
original document order (i.e. the left to right, top to bottom reading
order of English text).
"""
ordered_nodes = []
def recurse(node):
if not (node_types and not isinstance(nod... |
def is_in_list(num, lst):
"""
>>> is_in_list(5, [1, 2, 3, 4])
False
>>> is_in_list(5, [1, 5, 6])
True
"""
in_list = False
for item in lst:
if num == item:
in_list = True
break
return in_list |
def num_env_steps(infos):
"""Calculate number of environment frames in a batch of experience."""
total_num_frames = 0
for info in infos:
total_num_frames += info.get('num_frames', 1)
return total_num_frames |
def encode(val):
"""
Encode a string assuming the encoding is UTF-8.
:param: a unicode or bytes object
:returns: bytes
"""
if isinstance(val, (list, tuple)): # encode a list or tuple of strings
return [encode(v) for v in val]
elif isinstance(val, str):
return val.encode('ut... |
def sort_domains(domains):
"""
This function is used to sort the domains in a hierarchical order for
readability.
Args:
domains -- the list of input domains
Returns:
domains -- hierarchically sorted list of domains
"""
domainbits = [domain.lower().split('.') for domain in domains]
... |
def __partition2way__(arr, lo, hi):
"""
Function to achieve 2-way partitioning for quicksort
1. Start with 2 pointers lt and gt, choose first element (lo) as pivot
2. Invariant: everything to the left of lt is less than pivot, right of gt is larger than pivot
3. In each iteration, do the following i... |
def find_str_in_dict(
term, class_mapping):
"""Finds all key, value in class_mapping s.t key is a substring of term."""
all_matched_classes = []
for k, v in class_mapping.items():
if k in term.lower():
all_matched_classes.append((v, k))
return all_matched_classes |
def set_status(parameters):
"""Set status for a sample.
:param parameters: Collected parameters for a sample
:returns: string
"""
status = "N/A"
if 'rounded_read_count' in parameters.keys() and 'ordered_amount' in parameters.keys():
if parameters['rounded_read_count'] >= parameter... |
def decode_response(response_body):
"""Decode response body and return a unicode string."""
try:
response_body = response_body.decode('iso-8859-1', 'strict')
except UnicodeDecodeError:
print('decoding iso-8859-1 failed')
try:
response_body = response_body.decode('iso-8859... |
def _shift_interval_by(intervals, weight):
""" Shift the intervals by weight """
return [[x + weight, y + weight] for [x, y] in intervals] |
def divider(d):
"""Return decimal fraction of 1/d in array form."""
carry = 10
df = []
while carry:
if carry < d:
carry *= 10
df.append(0)
else:
df.append(carry // d)
carry = (carry % d)*10
return df |
def _ycc(r, g, b, a=None):
"""Conversion from rgba to ycc.
Notes:
Expects and returns values in [0,255] range.
"""
y = .299*r + .587*g + .114*b
cb = 128 - .168736*r - .331364*g + .5*b
cr = 128 + .5*r - .418688*g - .081312*b
if a is not None:
return [y, cb, cr, a]
else:
... |
def _filename(filename: str) -> str:
"""
Prepends some magic data to a filename in order to have long filenames.
.. warning:: This might be Windows specific.
"""
if len(filename) > 255:
return '\\\\?\\' + filename
return filename |
def headers(token):
"""heads up."""
headers_obj = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
return headers_obj |
def fitness_function(solution, answer):
"""fitness_function(solution, answer) Returns a fitness score of a solution compaired to the desired answer. This score is the absolute 'ascii' distance between characters."""
score =0
for i in range(len(answer)):
score += (abs(solution[i]-answer[i]))
retu... |
def func_args_p_kwargs(*args, p="p", **kwargs):
"""func.
Parameters
----------
args: tuple
p: str
kwargs: dict
Returns
-------
args: tuple
p: str
kwargs: dict
"""
return None, None, None, None, args, p, None, kwargs |
def check_fields_present(passport, validity_checks):
"""Check that all of the required fields are present as keys in the input dictionary"""
return validity_checks.keys() <= passport.keys() |
def noLOG(*args, **kwargs):
"""
does nothing
"""
if len(args) > 0:
return args[0]
return None |
def connect_streets(st1, st2):
"""
Tells if streets `st1`, `st2` are connected.
@param st1 street 1
@param st2 street 2
@return tuple or tuple (0 or 1, 0 or 1)
Each tuple means:
* 0 or 1 mean first or last extremity or the first street
* 0 or 1 mean first... |
def is_amex(card_num):
"""Return true if first two numbers are 34 or 37"""
first_nums = card_num[:2]
if int(first_nums) in (34, 37):
return True
return False |
def get_key_and_value(dict, lookup_value, value_loc):
""" Finds the key and associated value from the lookup value based on the location of the lookup value """
for key, value in dict.items():
if lookup_value == value[value_loc[0]][value_loc[1]]:
return key, value
return None, None |
def _build_code_script(langs):
""" Thx Prism for rendering Latex
"""
lang_prefix = '<script src="https://cdnjs.cloudflare.com/ajax/libs/prism\
/1.9.0/prism.min.js"></script>'
lang_temp = '<script src="https://cdnjs.cloudflare.com/ajax/libs/prism\
/1.9.0/components/prism-{}.min.js"></script>'
lang_sc... |
def compare_posts(fetched, stored):
"""
Checks if there are new posts
"""
i=0
for post in fetched:
if not fetched[post] in [stored[item] for item in stored]:
i+=1
return i |
def get_operating_systems(_os):
"""Helper Script to get operating systems."""
# Update and fix as more OS's converted to folder based tests
if _os:
return [_os]
return ["asa", "ios", "iosxe"]
# operating_system = []
# for folder in os.listdir("./"):
# if os.path.islink("./" + fold... |
def tochannel(room_name):
"""Convert a Stack room name into an idiomatic IRC channel name by downcasing
and replacing whitespace with hyphens.
"""
return '#' + room_name.lower().replace(' ', '-') |
def ordered_set(iterable):
"""Creates an ordered list from strings, tuples or other hashable items.
Returns:
list of unique and ordered values
"""
mmap = {}
ord_set = []
for item in iterable:
# Save unique items in input order
if item not in mmap:
mmap[item... |
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 p... |
def skip(s,n):
"""
Returns a copy of s, only including positions that are multiples of n
A position is a multiple of n if pos % n == 0.
Examples:
skip('hello world',1) returns 'hello world'
skip('hello world',2) returns 'hlowrd'
skip('hello world',3) returns 'hlwl'
skip... |
def _flatten_result(result):
"""
Ensure we can serialize a celery result.
"""
if issubclass(type(result), Exception):
return result.message
else:
return result |
def human_format(num):
"""Transfer count number."""
num = float('{:.3g}'.format(num))
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'),
['', 'K', 'M', 'B', 'T'][magnitude]) |
def filter_tags(tags, prefixes=None):
"""Filter list of relation tags matching specified prefixes."""
if prefixes is not None:
# filter by specified relation tag prefixes
tags = tuple( t for t in tags if any(( t.startswith(p) for p in prefixes )) )
return tags |
def unique(seq):
"""Return the unique elements of a collection even if those elements are
unhashable and unsortable, like dicts and sets"""
cleaned = []
for each in seq:
if each not in cleaned:
cleaned.append(each)
return cleaned |
def is_statevector_backend(backend):
"""
Return True if backend object is statevector.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is statevector
"""
return backend.name().startswith('statevector') if backend is not None else False |
def solve_polynom(a, b, c):
"""Solve a real polynom of degree 2.
:param a: coefficient for :math:`x^2`
:param b: coefficient for :math:`x`
:param c: coefficient for :math:`1`
:return: couple of solutions or one if the degree is 1.
"""
if a == 0:
# One degree.
return (-c / b... |
def parse_text(value: bytes) -> str:
"""Decode a byte string."""
return value.decode() |
def readable_time(seconds):
"""Converts a number of seconds to a human-readable time in seconds, minutes, and hours."""
parts = []
if seconds >= 86400: # 1 day
days = seconds // 86400
if days == 1:
parts.append("{} day".format(int(days)))
else:
parts.append(... |
def extract_catids(all_items):
"""
Function to extract category ids from a list of items
:param all_items: list of dicts containing item information
:return: list of categories
"""
category_ids = list()
for item in all_items:
if 'category_id' in item:
if item['category_i... |
def drift_forecast(submodel, horizon):
"""Computing the forecast for the drift model
"""
points = []
for h in range(horizon):
points.append(submodel["value"] + submodel["slope"] * (h + 1))
return points |
def parser_mod_shortname(parser):
"""Return short name of the parser's module name (no -- prefix and dashes converted to underscores)"""
return parser.replace('--', '').replace('-', '_') |
def _byte_str(num, unit='auto', precision=2):
"""
Automatically chooses relevant unit (KB, MB, or GB) for displaying some
number of bytes.
Args:
num (int): number of bytes
unit (str): which unit to use, can be auto, B, KB, MB, GB, or TB
References:
https://en.wikipedia.org/... |
def plus_one(nums):
"""write a program which takes as input an array of digits encoding a non negative
decimal integer D and updates the array to represent D+1. For example (1,2,9)->(1,3,0)
Args:
nums (array): [array of integer]
"""
nums[-1] += 1
n = len(nums)
for i in range(n-1,... |
def wordPairDist(word1, word2, words):
"""word pair distance counts the number
of words which lie between those of a given pair.
"""
if word1 in words and word2 in words:
return abs(words.index(word1) - words.index(word2))
return -1 |
def binary_search(arr, value):
""" Binary Search takes array and value to search """
""" returns index or-1"""
count = len(arr)
midpoint = count // 2
start_index = 0
end_index = count - 1
while value != arr[start_index+midpoint] and count > 1:
# import pdb; pdb.set_trace()
if... |
def ShellCommand(cc_compiler_path, command_line_list = []):
"""Shell command that lists the compiler info and include directories
Returns:
string: shell command to run
"""
return [cc_compiler_path, "-E", "-x", "c++"] + command_line_list + ["-", "-v", "/dev/null"] |
def rightrotate_64(x, c):
""" Right rotate the number x by c bytes, for 64-bits numbers."""
x &= 0xFFFFFFFFFFFFFFFF
return ((x >> c) | (x << (64 - c))) & 0xFFFFFFFFFFFFFFFF |
def add_switch_to_cache(cache, switch):
"""Add a switch to the cache.
Args:
cache: The JSON representation of the current YAML cache file.
switch: The JSON switch object to be added to the cache.
Returns:
The updated JSON cache with the switch appended
"""
# If there are no... |
def getx(data, keys, default=None, validator=None):
""" extended get of an attribute of the cluster API with, recoursion (deep get), defaulting & validation """
for key in keys.split('.'):
try:
data = data[key]
except KeyError:
if default != None:
return ... |
def get_encoding_from_witness(witness_type=None):
"""
Derive address encoding (base58 or bech32) from transaction witness type.
Returns 'base58' for legacy and p2sh-segwit witness type and 'bech32' for segwit
:param witness_type: Witness type: legacy, p2sh-segwit or segwit
:type witness_type: str
... |
def pretty_size(size_in_bytes=0, measure=None):
"""Pretty format filesize/size_in_bytes into human-readable strings.
Maps a byte count to KiB, MiB, GiB, KB, MB, or GB. By default,
this measurement is automatically calculated depending on filesize,
but can be overridden by passing `measure` key.
Ar... |
def get_hostlist_by_range(hoststring, prefix='', width=0):
"""Convert string with host IDs into list of hosts.
Example: Cobalt RM would have host template as 'nid%05d'
get_hostlist_by_range('1-3,5', prefix='nid', width=5) =>
['nid00001', 'nid00002', 'nid00003', 'nid00005']
"... |
def string_to_list(string, sep=","):
"""Transforma una string con elementos separados por `sep` en una lista."""
return [value.strip() for value in string.split(sep)] |
def _from_str_to_dict(raw_data: str) -> dict:
"""Assume format `key1: value1, key2: value2, ...`."""
raw_pairs = raw_data.split(",")
def _parse_item(raw_key: str):
return raw_key.lstrip(" ").rstrip(" ").rstrip(":")
data_out = {}
for pair in raw_pairs:
if ":" not in pair:
... |
def all_tasks_finished(tasks):
"""Returns True if all rq jobs are finished."""
for task in tasks:
job = task.get_rq_job()
if job is None:
# if job is not in queue anymore, it finished successfully
continue
if not job.is_finished:
return False
retur... |
def convert_words_to_id(corpus, word2id):
"""Convert list of words to list of corresponding id.
Args:
corpus: a list of str words.
word2id: a dictionary that maps word to id.
Returns:
converted corpus, i.e., list of word ids.
"""
new_corpus = [-1] * len(corpus)
for i, wo... |
def to_pixel_units(l, pixelwidth):
"""Scales length l to pixel units, using supplied
pixel width in arbitrary length units
"""
try:
return l / pixelwidth
except (TypeError, ZeroDivisionError):
return l |
def recolor_by_frequency(colors: dict) -> dict:
"""
Use the information that 0 and 1 color will be close for us and info about the frequencies of similar objects
to change the colors to new ones
Args:
colors: dict, old coloring
Returns:
dict, new coloring, that uses that 0 and 1 is ... |
def account_warning_and_deletion_in_weeks_are_correct( # noqa
deletion_weeks: int, warning_weeks: tuple
) -> bool:
""" Validates variables INACTIVE_ACCOUNT_DELETION_IN_WEEKS
and INACTIVE_ACCOUNT_WARNING_IN_WEEKS.
INACTIVE_ACCOUNT_DELETION_IN_WEEKS must not be
zero or less than one of IN... |
def posofend(str1, str2):
"""returns the position immediately _after_ the end of the occurence
of str2 in str1. If str2 is not in str1, return -1.
"""
pos = str1.find(str2)
if pos>-1:
ret= pos+len(str2)
else:
ret = -1
return ret |
def correct_protein_name_list(lst):
""" Correct a list of protein names with incorrect separators involving '[Cleaved into: ...]'
Args:
lst (:obj:`str`): list of protein names with incorrect separators
Returns:
:obj:`str`: corrected list of protein names
"""
if lst:
lst = l... |
def _EscapeArgText(text):
"""Escape annotation argument text.
Args:
text: String to escape.
"""
return text.replace('@', '-AT-') |
def merge_two_dicts(x, y):
"""
Given two dicts, merge them into a new dict as a shallow copy
"""
z = x.copy()
z.update(y)
return z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.