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
remaining tags (like <ul>, <CITE>, etc.). This is done using simple
regular expressions, but could probably be done more robustly by
the method detailed in
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52281 .
"""
import re
clean_defs = []
LI_re = re.compile(r'<LI[^>]*>(.*)</LI>')
HTML_re = re.compile(r'<[^>]+>\s*')
defs = LI_re.findall(text)
# remove internal tags
for d in defs:
clean_d = HTML_re.sub('',d)
if clean_d: clean_defs.append(clean_d)
return clean_defs
|
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)
return o_set
|
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, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
)
def roman_num(num):
for r, ltr in roman:
x, _ = divmod(num, r)
yield ltr * x
num -= r * x
if num <= 0:
break
return "".join([a for a in roman_num(num)])
|
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
"""
# Check through the IP IOCs
return [ioc for ioc in (indicators or []) if ioc in known_iocs]
|
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 len(questions)
|
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,
'relative_tolerance': rtol,
'maximum_iterations': int(maxiter),
}
return {'phi_1': demag_params, 'phi_2': demag_params}
|
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-qubit teleport
targets.append({'0 0 0': shots / 4, '0 0 1': shots / 4,
'0 1 0': shots / 4, '0 1 1': shots / 4})
return targets
|
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)) & (0x0101010101010101)
return longbits
|
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
-------
kappa1 : float
constant kappa1 in the PWP equation (cm/s)
"""
kappa1 = 10.**(0.198 - 444./T_K)
return kappa1
|
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_dimA = matrix_A_dim
else:
batch_w = matrix_A_dim // split_dim + 1
if matrix_G_dim % split_dim == 0:
batch_h = matrix_G_dim // split_dim
else:
if matrix_G_dim < split_dim:
batch_h = 1
split_dimG = matrix_G_dim
else:
batch_h = matrix_G_dim // split_dim + 1
matrix_A_shape = (batch_h, batch_w, split_dimA, split_dimA)
matrix_G_shape = (batch_h, split_dimG, split_dimG)
return matrix_A_shape, matrix_G_shape
|
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 string (unset).
:type data: String
:param data: The cookie serialized data that is going to be parsed
in order to create the final cookie dictionary/map.
:rtype: Dictionary
:return: The final map containing key the value association for the
various parts of the provided cookie string.
"""
# creates the dictionary that is going to hold the various cookie
# key to value associations parsed from the "raw" data
cookie_m = dict()
# splits the data information around the proper cookie separator
# and then iterates over each of the cookies to set them in the
# final cookie map (with the key to value associations)
cookies = [cookie.strip() for cookie in data.split(";")]
for cookie in cookies:
if not "=" in cookie: cookie += "="
name, value = cookie.split("=", 1)
cookie_m[name] = value
# returns the final map of cookies to the caller method so that
# proper and easy access is possible to the cookie
return cookie_m
|
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 the input value is not of type `dict` or `list`, the value will be returned as-is.
Args:
inValue (any): The dict to mutate.
keyFn (lambda): The function to apply to keys.
valueFn (lambda): The function to apply to values.
keyTypes (tuple, optional): If set, only keys of these types will be mutated
with ``keyFn``.
valueTypes (tuple, optional): If set, only values of these types will be mutated
with ``valueFn``.
Returns:
A recursively mutated dict, list of dicts, or the value as-is (described above).
"""
# this is here as a way of making sure that the various places where recursion is done always
# performs the same call, preserving all arguments except for value (which is what changes
# between nested calls).
def recurse(value):
return mutate_dict(
value,
keyFn=keyFn,
valueFn=valueFn,
keyTypes=keyTypes,
valueTypes=valueTypes,
**kwargs
)
# handle dicts
if isinstance(inValue, dict):
# create the output dict
outputDict = dict()
# for each dict item...
for k, v in inValue.items():
# apply the keyFn to some or all of the keys we encounter
if keyTypes is None or (isinstance(keyTypes, tuple) and isinstance(k, keyTypes)):
# prepare the new key
k = keyFn(k, **kwargs)
# apply the valueFn to some or all of the values we encounter
if valueTypes is None or (isinstance(valueTypes, tuple) and isinstance(v, valueTypes)):
v = valueFn(v)
# recurse depending on the value's type
#
if isinstance(v, dict):
# recursively call mutate_dict() for nested dicts
outputDict[k] = recurse(v)
elif isinstance(v, list):
# recursively call mutate_dict() for each element in a list
outputDict[k] = [recurse(i) for i in v]
else:
# set the value straight up
outputDict[k] = v
# return the now-populated output dict
return outputDict
# handle lists-of-dicts
elif isinstance(inValue, list) and len(inValue) > 0:
return [recurse(i) for i in inValue]
else:
# passthrough non-dict value as-is
return inValue
|
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
return key_in_string
|
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) + len(set2) - inter)
|
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 pokemon's stat.
"""
return max(2, 2 + pokemon["boosts"][stat_name]) / \
max(2, 2 - pokemon["boosts"][stat_name])
|
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 string.split(",")]
return string_list
|
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 term component.
Notes
-----
- This function deals with empty list inputs.
- This function adds "" to terms to make them exact search only.
- This function replaces any spaces in terms with '+'.
"""
comp = ''
if terms and terms[0]:
terms = ['"'+ item + '"' for item in terms]
comp = '(' + joiner.join(terms) + ')'
comp = comp.replace(' ', '+')
return comp
|
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:
return i
return iterMax
|
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_ids)
|
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 = text.replace("–", "-")
return 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
leading/trailing spaces.
You may assume the input only contain English
alphabet and spaces.
:param s:
:return:
"""
s_arr = s.split(' ')[::-1]
for i, word in enumerate(s_arr):
s_arr[i] = ''.join((char.upper() if char.islower() else char.lower()) for char in word)
return ' '.join(s_arr)
|
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:
--------
Node: The specific node from the list.
"""
for node in nodes:
if node.number==i:
return node
|
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 + 45):
return 0
elif yaw_normalized >= 0 + 45 and yaw_normalized < 90 + 45:
return 90
elif yaw_normalized >= 90 + 45 and yaw_normalized < 180 + 45:
return 180
else:
return -90
|
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] != '"':
return False
char = '"' if line[0] == '"' else "'"
index_of_last_quote = line.index(char, line.index(char) + 1)
return line[index_of_last_quote + 1] == ','
|
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(node, node_types)):
ordered_nodes.append(node)
for child in getattr(node, 'contents', []):
recurse(child)
recurse(root)
return ordered_nodes
|
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('utf-8')
else:
# assume it was an already encoded object
return val
|
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]
for domain in domainbits:
domain.reverse()
sorted(domainbits)
domains = [('.'.join(reversed(domain))) for domain in sorted(domainbits)]
return 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 in order:
(a) Increment lt until arr[lt] >= arr[lo]
(b) Decrement gt until arr[gt] <= arr[lo]
(c) Check if pointers have crossed (gt<=lt),
if yes then swap arr[lo] with arr[gt] and break out
(d) If pointers didn't cross, then swap arr[lt] with arr[gt]
4. Return the index of the pivot (now gt) so that it can be used by __quicksortHelper__
"""
if lo >= hi:
return
# Define lt and gt pointers
lt = lo
gt = hi + 1
while True:
while lt < hi:
lt += 1
if arr[lt] >= arr[lo]:
# print("Break lt at ", lt)
break
while gt > lo:
gt -= 1
if arr[gt] < arr[lo]:
# print("Break gt at ", gt)
break
if gt <= lt:
arr[lo], arr[gt] = arr[gt], arr[lo]
break
if arr[lt] > arr[gt]:
# print(f"swap {arr[lt]} with {arr[gt]}")
arr[lt], arr[gt] = arr[gt], arr[lt]
# print(arr)
return gt
|
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'] >= parameters['ordered_amount']:
status = "P"
else:
status = None
return status
|
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-15', 'strict')
except UnicodeDecodeError:
print('decoding iso-8859-15 failed, too')
response_body = response_body.decode('windows-1252', 'replace')
return response_body
|
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:
return [y, cb, cr]
|
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]))
return score
|
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 or last extremity or the second street
``((0, 1),)`` means the first point of the first street is connected
to the second extremity of the second street.
"""
a1, b1 = st1[0], st1[-1]
a2, b2 = st2[0], st2[-1]
connect = []
if a1 == a2:
connect.append((0, 0))
if a1 == b2:
connect.append((0, 1))
if b1 == a2:
connect.append((1, 0))
if b1 == b2:
connect.append((1, 1))
return tuple(connect) if connect else None
|
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_scripts = [lang_prefix]
for lang in langs:
lang_scripts.append(lang_temp.format(lang))
return '\n'.join(lang_scripts)
|
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("./" + folder):
# operating_system.append(folder)
# return operating_system
|
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] = 1
ord_set.append(item)
return ord_set
|
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):
data = item[field_name]
else:
data = getattr(item, field_name, '')
if data is None:
data = ''
row.append(data)
return tuple(row)
|
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('hello world',4) returns 'hor'
Parameter s: the string to copy
Precondition: s is a nonempty string
Parameter n: the letter positions to accept
Precondition: n is an int > 0
"""
assert type(s) == str and len(s) > 0
assert type(n) == int and n > 0
# You must use a while-loop, not a for-loop
var = []
var2 = True
pos = 0
count = 1
while var2:
if pos % n == 0 and count <= len(s):
var.append(s[pos])
pos += 1
count += 1
elif pos % n != 0 and count <= len(s):
pos += 1
count += 1
else:
var2 = False
return ''.join(var)
#pass
|
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, )
det = b * b - (4 * a * c)
if det < 0:
# No real solution.
return None
det = det ** 0.5
x1 = (b - det) / (2 * a)
x2 = (b + det) / (2 * a)
return x1, x2
|
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("{} days".format(int(days)))
if seconds >= 3600: # 1 hour
hours = seconds // 3600 % 24
if hours == 1:
parts.append("{} hour".format(int(hours)))
else:
parts.append("{} hours".format(int(hours)))
if seconds >= 60: # 1 hour
minutes = seconds // 60 % 60
if minutes == 1:
parts.append("{} minute".format(int(minutes)))
else:
parts.append("{} minutes".format(int(minutes)))
seconds = round(seconds % 60, 2)
if seconds == 1:
parts.append("{} second".format(seconds))
else:
parts.append("{} seconds".format(seconds))
return ", ".join(parts)
|
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_id'] not in category_ids and item['category_id']:
category_ids.append(item['category_id'])
return category_ids
|
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/wiki/Orders_of_magnitude_(data)
Returns:
str: string representing the number of bytes with appropriate units
Example:
>>> import ubelt as ub
>>> num_list = [1, 100, 1024, 1048576, 1073741824, 1099511627776]
>>> result = ub.repr2(list(map(_byte_str, num_list)), nl=0)
>>> print(result)
['0.00KB', '0.10KB', '1.00KB', '1.00MB', '1.00GB', '1.00TB']
>>> _byte_str(10, unit='B')
10.00B
"""
abs_num = abs(num)
if unit == 'auto':
if abs_num < 2.0 ** 10:
unit = 'KB'
elif abs_num < 2.0 ** 20:
unit = 'KB'
elif abs_num < 2.0 ** 30:
unit = 'MB'
elif abs_num < 2.0 ** 40:
unit = 'GB'
else:
unit = 'TB'
if unit.lower().startswith('b'):
num_unit = num
elif unit.lower().startswith('k'):
num_unit = num / (2.0 ** 10)
elif unit.lower().startswith('m'):
num_unit = num / (2.0 ** 20)
elif unit.lower().startswith('g'):
num_unit = num / (2.0 ** 30)
elif unit.lower().startswith('t'):
num_unit = num / (2.0 ** 40)
else:
raise ValueError('unknown num={!r} unit={!r}'.format(num, unit))
fmtstr = ('{:.' + str(precision) + 'f}{}')
res = fmtstr.format(num_unit, unit)
return res
|
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, -1, -1):
if nums[i] != 10:
break
nums[i] = 0
nums[i-1] += 1
if nums[0] == 10:
nums[0] = 1
nums.append(0)
return nums
|
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 value > arr[midpoint+start_index]:
start_index = midpoint
count = count - (midpoint)
midpoint = count // 2
else:
end_index = end_index - midpoint
count = count - midpoint
midpoint = count // 2
if value == arr[midpoint+start_index]:
return midpoint + start_index
else:
return -1
|
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 switches yet in the cache
if cache["switches"] is None: # pragma: no cover
cache["switches"] = [switch]
else:
cache["switches"].append(switch)
return cache
|
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 default
else:
raise KeyError("invalid cluster API definition. Key '%s' does not exist" % (keys))
if validator != None:
validator(data)
return data
|
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
:return str:
"""
if witness_type == 'segwit':
return 'bech32'
elif witness_type in [None, 'legacy', 'p2sh-segwit']:
return 'base58'
else:
raise ValueError("Unknown witness type %s" % witness_type)
|
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.
Args:
size_in_bytes (int): file size in bytes
measure (str, utf-8): (optional) key value for the pretty_size_map to force
formatting to a specific measurement.
Returns:
A human-readable formatted filesize string.
"""
# Force size_in_bytes to be an integer
size_in_bytes = size_in_bytes or 0
# Map out the math required to re-calculate bytes into human-readable formats.
pretty_size_map = {
# Do not round.
"B": size_in_bytes,
# Round to nearest whole number.
"KB": round(size_in_bytes / 1000.0, 0),
"KiB": round(size_in_bytes / 1024.0, 0),
# Round to one decimal place.
"MB": round(size_in_bytes / 1000.0 / 1000.0, 1),
"MiB": round(size_in_bytes / 1024.0 / 1024.0, 1),
# Round to two decimal places.
"GB": round(size_in_bytes / 1000.0 / 1000.0 / 1000.0, 2),
"GiB": round(size_in_bytes / 1024.0 / 1024.0 / 1024.0, 2)
}
# If measure was specified, format and return. This is usually used when calling
# this function recursively, but can be called manually.
if measure:
return f'{pretty_size_map[measure]} {measure}'
elif pretty_size_map['GiB'] > 1:
return pretty_size(size_in_bytes, 'GiB')
elif pretty_size_map['MiB'] > 1:
return pretty_size(size_in_bytes, 'MiB')
elif pretty_size_map['KiB'] > 1:
return pretty_size(size_in_bytes, 'KiB')
else:
return f'{size_in_bytes:,.0f} B'
|
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']
"""
if not hoststring.replace('-', '').replace(',', '').isnumeric():
raise ValueError('non numeric set of ranges (%s)' % hoststring)
host_ids = []
id_width = 0
for num in hoststring.split(','):
num_range = num.split('-')
if len(num_range) > 1:
num_lo, num_hi = num_range
if not num_lo or not num_hi:
raise ValueError('incorrect range format (%s)' % num)
host_ids.extend(list(range(int(num_lo), int(num_hi) + 1)))
else:
host_ids.append(int(num_range[0]))
id_width = max(id_width, *[len(n) for n in num_range])
width = width or id_width
return ['%s%0*d' % (prefix, width, hid) for hid in host_ids]
|
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:
break
key, value = pair.split(":", maxsplit=1)
data_out[_parse_item(key)] = _parse_item(value)
return data_out
|
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
return True
|
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, word in enumerate(corpus):
if word in word2id:
new_corpus[i] = word2id[word]
return new_corpus
|
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 close colors
"""
replace_dict = {val: ind for ind, val in
enumerate(sorted(set(colors.values()), key=lambda x: list(colors.values()).count(colors[x])))}
result_dict = {}
for key in colors:
result_dict[key] = replace_dict[colors[key]]
return result_dict
|
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 INACTIVE_ACCOUNT_WARNING_IN_WEEKS.
Check if INACTIVE_ACCOUNT_DELETION_IN_WEEKS is an integer.
Also check if INACTIVE_ACCOUNT_WARNING_IN_WEEKS is a tuple with two integers.
If one of the conditions is not satisfied, returns False else True.
"""
if deletion_weeks is not None and (
type(deletion_weeks) != int or deletion_weeks == 0
):
return False
if warning_weeks is not None:
if type(warning_weeks) == tuple and len(warning_weeks) == 2:
first_week_warning = warning_weeks[0]
second_week_warning = warning_weeks[1]
if (
(not first_week_warning or not second_week_warning)
or first_week_warning >= second_week_warning
or (type(first_week_warning) != int or type(second_week_warning) != int)
):
return False
else:
return False
if deletion_weeks is not None:
if (
deletion_weeks <= first_week_warning
or deletion_weeks <= second_week_warning
):
return False
return True
|
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 = lst.replace('[Cleaved into: Nuclear pore complex protein Nup98;',
'[Cleaved into: Nuclear pore complex protein Nup98];')
lst = lst.replace('[Cleaved into: Lamin-A/C;',
'[Cleaved into: Lamin-A/C];')
lst = lst.replace('[Cleaved into: Lamin-A/C ;',
'[Cleaved into: Lamin-A/C ];')
lst = lst.replace('[Includes: Maltase ;', '[Includes: Maltase ];')
return lst
|
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.