content stringlengths 42 6.51k |
|---|
def _add_payload_files(zip_file, payload_info_list):
"""Add the payload files to the zip."""
payload_byte_count = 0
payload_file_count = 0
for payload_info_dict in payload_info_list:
zip_file.write_iter(payload_info_dict["path"], payload_info_dict["iter"])
payload_byte_count += payload_info_dict["iter"].size
payload_file_count += 1
return payload_byte_count, payload_file_count |
def expand_alsa_port_name(port_names, name):
"""Expand ALSA port name.
RtMidi/ALSA includes client name and client:port number in
the port name, for example:
TiMidity:TiMidity port 0 128:0
This allows you to specify only port name or client:port name when
opening a port. It will compare the name to each name in
port_names (typically returned from get_*_names()) and try these
three variants in turn:
TiMidity:TiMidity port 0 128:0
TiMidity:TiMidity port 0
TiMidity port 0
It returns the first match. If no match is found it returns the
passed name so the caller can deal with it.
"""
if name is None:
return None
for port_name in port_names:
if name == port_name:
return name
# Try without client and port number (for example 128:0).
without_numbers = port_name.rsplit(None, 1)[0]
if name == without_numbers:
return port_name
if ':' in without_numbers:
without_client = without_numbers.split(':', 1)[1]
if name == without_client:
return port_name
else:
# Let caller deal with it.
return name |
def parse_bool(raw):
"""Takes a string representation of a truthy string value and converts it to bool.
Valid boolean representations include:
- y/yes/Yes/YES
- true/True/TRUE
- 1
Args:
raw (str): Truthy value to convert.
Returns:
bool: Boolean representation of value.
"""
if isinstance(raw, str):
raw = raw.lower()
return raw in ["y", "yes", "true", "1", 1] |
def calc_conformance(results):
"""Returns a tuple with the number of total and failed testcase variations and the conformance as percentage."""
total = len(results)
failed = sum(1 for status, _ in results.values() if status != 'PASS')
conformance = (total-failed)*100/total if total > 0 else 100
return total, failed, conformance |
def func_a_args_kwargs(a=2, *args, **kwargs):
"""func.
Parameters
----------
a: int
args: tuple
kwargs: dict
Returns
-------
a: int
args: tuple
kwargs: dict
"""
return None, None, a, None, args, None, None, kwargs |
def bucket_sort(elements, bucket_size=10):
"""
Use the simple bucket sort algorithm to sort the :param elements.
:param bucket_size: the distribution buckets' size
:param elements: a integer sequence in which the function __get_item__ and __len__ were implemented()
:return: the sorted elements in increasing order
"""
length = len(elements)
if not length or length == 1:
return elements
mini = maxi = elements[0]
for element in elements:
assert isinstance(element, int)
if element < mini:
mini = element
if element > maxi:
maxi = element
buckets_size = (maxi - mini + 1) // bucket_size
if (maxi - mini + 1) % bucket_size:
buckets_size += 1
buckets = []
for i in range(buckets_size):
buckets.append([None, None])
for element in elements:
index = element // bucket_size
ptr = buckets[index]
while ptr[1] and ptr[1][0] < element:
ptr = ptr[1]
element = [element, ptr[1]]
ptr[1] = element
length = 0
for bucket in buckets:
ptr = bucket[1]
while ptr:
elements[length] = ptr[0]
length += 1
ptr = ptr[1]
return elements |
def _create_url(searchword, area):
""" Creates the url for the web page to scrape. """
return 'https://www.blocket.se/{}?q={}&cg=0&w=1&st=s&c=&ca=15&is=1&l=0&md=th'.format(area, searchword) |
def validate_image(layer_list):
"""
Takes list of image layer strings.
Validates image layer data by finding the layer with the fewest 0 digits,
and then determines and returns the number of 1 digits multiplied by the number
of 2 digits in that layer.
"""
min_count = 150
best_layer = -1
for i in range(len(layer_list)):
zeroes = layer_list[i].count('0')
if zeroes < min_count:
min_count = zeroes
best_layer = i
return layer_list[best_layer].count('1') * layer_list[best_layer].count('2') |
def get_all_ngrams(sequence, n):
"""
Creates a list of all ngrams found in a given sequence.
Example
---------
>>> sequence = [2,1,1,4,2,2,3,4,2,1,1]
>>> ps.get_unique_ngrams(sequence, 3) #doctest: +NORMALIZE_WHITESPACE
[[2, 1, 1],
[1, 1, 4],
[1, 4, 2],
[4, 2, 2],
[2, 2, 3],
[2, 3, 4],
[3, 4, 2],
[4, 2, 1]]
"""
all_ngrams = []
for x in range(len(sequence) - n + 1):
this_ngram = sequence[x:x + n]
all_ngrams.append(this_ngram)
return all_ngrams |
def eval_callbacks(callbacks, result):
"""Evaluate list of callbacks on result.
The return values of the `callbacks` are ORed together to give the
overall decision on whether or not the optimization procedure should
continue.
Parameters
----------
callbacks : list of callables
Callbacks to evaluate.
result : `OptimizeResult`, scipy object
Optimization result object to be stored.
Returns
-------
decision : bool
Decision of the callbacks whether or not to keep optimizing
"""
stop = False
if callbacks:
for c in callbacks:
decision = c(result)
if decision is not None:
stop = stop or decision
return stop |
def is_valid_data_node(data_dict):
"""Checks whether the json data node is valid."""
# Check if json element is a dict
if type(data_dict) != dict:
return False
# Check if only data element is present in the dict
if len(data_dict) != 1:
return False
# Try to parse the string key to int
try:
int(list(data_dict)[0])
return True
except ValueError:
return False |
def R_from_r(r):
"""
Calculate reflected power R from the reflection amplitude r
of the Fresnel equations.
Parameters
----------
r : array like
Fresnel reflection coefficients
Returns
-------
R : array like
Reflectivity
"""
return abs(r)**2 |
def binary_search(l, target):
"""
given a sorted list 'l' and a target value, return the position of target
in the list or None if not found.
"""
i = 0
j = len(l)
while j>i:
m = (j-i)//2 + i
if l[m] == target:
return m
elif l[m] < target:
i = m+1
else:
j = m
return None |
def schedd_states(schedd_classad):
"""
Returns information about the number of jobs in each job state for a schedd
:param schedd_classad: classad for schedd to query
:return: a dictionary with job states as keys and number of jobs in
given state as a value
"""
return {'Running': schedd_classad['TotalRunningJobs'],
'Idle': schedd_classad['TotalIdleJobs'],
'Held': schedd_classad['TotalHeldJobs'],
'Removed': schedd_classad['TotalRemovedJobs']} |
def rgb_to_hex(rgb):
"""Converts a RGB tuple or list to an hexadecimal string"""
return '#' + ''.join([(hex(c).split('x')[-1].zfill(2)) for c in rgb]) |
def max_key(dic):
"""
Based on https://stackoverflow.com/questions/42044090/return-the-maximum-value-from-a-dictionary
Returns the key of the max value in a dictionairy
"""
return [k for k, v in dic.items() if v == max(dic.values())][0] |
def is_unique(string):
"""Determines if a string is unique.
Args:
string: any string of characters.
Returns:
a Boolean value dependant on the uniqueness
Raises:
ValueError: Empty string value given as an argument
"""
temp = list()
if string:
for character in string:
if character in temp:
return False
temp.append(character)
return True
raise ValueError('string: value is empty') |
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
if len(dna1) > len(dna2):
return True
else:
return False |
def greet(name: str) -> dict:
"""
Greet the current user.
:param name: Name of the user
:return: Object: message to the user
"""
return {"message": f"Hello, {name}!"} |
def _rec_validate(f, g, i, K):
"""Recursive helper for :func:`dmp_validate`."""
if type(g) is not list:
if K is not None and not K.of_type(g):
raise TypeError("%s in %s in not of type %s" % (g, f, K.dtype))
return {i - 1}
elif not g:
return {i}
else:
levels = set()
for c in g:
levels |= _rec_validate(f, c, i + 1, K)
return levels |
def merge_headers(header_map_list):
"""
Helper function for combining multiple header maps into one.
:param header_map_list: list of maps
"""
headers = {}
for header_map in header_map_list:
headers.update(header_map)
return headers |
def fmt_class(text: str, cls: str) -> str:
"""Format a string in a certain class (`<span>`).
Args:
text: The text to format.
cls: The name of the class.
Returns:
A `<span>` with a class added.
"""
return f'<span class="{cls}">{text}</span>' |
def rgb_norm(val):
"""Pixel normalization
Function equivalent to keras.application.inception_v3.preprocess_input
Arguments:
val {int} -- Pixel value (0:255 range)
Returns:
int -- Pixel normalized value (-1:1 range)
"""
return 2/255*(val-255)+1 |
def readable_timedelta(days):
""" Display days in a human readable way
original function by Syed Marwan Jamal
Arguments:
- days : (int) amount of day to translate
Returns:
- : (str) human readable string with date
"""
number_of_weeks = days // 7
number_of_days = days % 7
return '{} week(s) and {} day(s)'.format(number_of_weeks, number_of_days) |
def remove_keys(obj, rubbish):
"""Recursively remove keys whose are in `rubbish` and return cleaned object"""
if isinstance(obj, dict):
obj = {
key: remove_keys(value, rubbish)
for key, value in obj.items()
if key not in rubbish}
elif isinstance(obj, list):
obj = [remove_keys(item, rubbish)
for item in obj
if item not in rubbish]
return obj |
def alternator(iterable, frontFirst=True):
"""
Alternates an iterable from front to back and returns the alternation as a list.
Example:
[0, 1, 2, 3, 4, 5]
turns into
[0, 5, 1, 4, 2, 3] if frontFirst is True and
[5, 0, 4, 1, 3, 2] if frontFirst is False.
Args:
iterable (iterable): some iterable to alternate.
frontFirst (bool, optional): whether to use the front element first or the
back element first. Defaults to True, so front element first.
Returns:
list: the alternated iterable.
"""
res = iterable.copy()
idx = 0
flipper = frontFirst
while len(iterable) > 0:
if flipper:
res[idx] = iterable.pop(0)
else:
res[idx] = iterable.pop(-1)
flipper = not flipper
idx += 1
return res |
def _MergeDeps(dest, update):
"""Merge the dependencies specified in two dictionaries.
Arguments:
dest: The dictionary that will be merged into.
update: The dictionary whose elements will be merged into dest.
"""
assert(not set(dest.keys()).intersection(set(update.keys())))
dest.update(update)
return dest |
def selection_sort_counting(A):
"""Instrumented Selection Sort to return #swaps, #compares."""
N = len(A)
num_swap = num_compare = 0
for i in range(N-1):
min_index = i
for j in range(i+1, N):
num_compare += 1
if A[j] < A[min_index]:
min_index = j
num_swap += 1
A[i],A[min_index] = A[min_index],A[i]
return (num_swap, num_compare) |
def clamp(n, lower, upper):
"""
:param n: Number to clamp
:param lower: Lower bound
:param upper: Upper bound
:return: Clamped number
"""
return max(lower, min(n, upper)) |
def _is_chrome_only_build(revision_to_bot_name):
"""Figures out if a revision-to-bot-name mapping represents a Chrome build.
We assume here that Chrome revisions are always > 100000, whereas WebRTC
revisions will not reach that number in the foreseeable future."""
revision = int(revision_to_bot_name.split('--')[0])
bot_name = revision_to_bot_name.split('--')[1]
return bot_name == 'Chrome' and revision > 100000 |
def area(span: float, aspect: float) -> float:
"""Calculates the surface area using ``span`` and ``aspect``."""
return span ** 2 / aspect |
def _scalarize(value):
"""Scalarize a value.
If VALUE is a list that consists of a single element, return that
element. Otherwise return VALUE."""
if type(value) == list and len(value) == 1:
return value[0]
return value |
def div(value, arg):
"""Division
>>> div(4, 2)
2
"""
if arg is None:
return 0
elif arg is 0:
return 0
else:
return value / arg |
def unsigned_int(value):
"""
Converts the given byte value to an unsigned integer.
"""
return int.from_bytes(bytearray(value), 'little') |
def daylight_hours(ws):
"""
:param ws: sunset hour angle [rad]
:return: daylight hours [hour]
"""
# 24.0 / pi = 7.639437268410976
return 7.639437268410976 * ws |
def dev_notifications_showing(dev0):
"""
m05.show the notifications.....
return none.........
"""
try:
dev0.open_notification()
except Exception as e:
print("error at dev_notifications_showing.")
pass
else:
pass
finally:
return None |
def get_least_edge_in_bunch(edge_bunch, weight='weight'):
"""
Edge bunch must be of the format (u, v, d) where u and v are the tail and head nodes (respectively) and d is a list
of dicts holding the edge_data for each edge in the bunch
todo: add this to some sort of utils file/ module in wardbradt/networkx
"""
if len(edge_bunch[2]) == 0:
raise ValueError("Edge bunch must contain more than one edge.")
least = {weight: float('Inf')}
for data in edge_bunch[2]:
if data[weight] < least[weight]:
least = data
return least |
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
if sum(nums) < 0:
return max(nums)
current_max = 0
total_max = 0
i = 0
while i < len(nums):
current_max = current_max + nums[i]
if current_max > total_max:
total_max = current_max
i += 1
return total_max |
def get_class_path(cls, use_tfds_prefix=True):
"""Returns path of given class or object. Eg: `tfds.image.cifar.Cifar10`."""
if not isinstance(cls, type):
cls = cls.__class__
module_path = cls.__module__
if use_tfds_prefix and module_path.startswith('tensorflow_datasets'):
module_path = 'tfds' + module_path[len('tensorflow_datasets'):]
return '.'.join([module_path, cls.__name__]) |
def one_to_three(one_letter):
"""
Convert a one letter code amino acid to a three letter code.
"""
assert one_letter.upper() in "FLSYCWPHERIMTNKVADQG*U", "Error, %s is not a valid amino acid" % one_letter
AA = {
"I": "Ile",
"V": "Val",
"L": "Leu",
"F": "Phe",
"C": "Cys",
"M": "Met",
"A": "Ala",
"G": "Gly",
"T": "Thr",
"W": "Trp",
"S": "Ser",
"Y": "Tyr",
"P": "Pro",
"H": "His",
"E": "Glu",
"Q": "Gln",
"D": "Asp",
"N": "Asn",
"K": "Lys",
"R": "Arg",
"*": "***",
"U": "Uaa",
} # Uaa = unnatural amino acid
return AA[one_letter.upper()] |
def get_integer_form(elem_list):
"""For an element list like ['e1', 'a1_2', 'a1_1', 'a1_3'],
return the integer 213, i.e., the 'subscripts' of the elements that
follow the identity element."""
return int(''.join(map(lambda x: x.split("_")[1], elem_list[1:]))) |
def reverse_bits(v, bits):
""" Do bit reversal operation.
Example input (8 bits case):
11100001
10000111
"""
y = 0
pos = bits - 1
while pos > 0:
y += ((v & 1) << pos)
v >>= 1
pos -= 1
return y |
def get_cached_small_value(*args, **kwargs):
"""
Non-decorated base implementation of a method that fetches a property from
a method of a class.
Method receives
"""
prop, method, *args = args
if isinstance(method, str):
fn = getattr(prop, method)
else:
fn = method.__get__(prop)
return fn(*args, **kwargs) |
def rows_to_pages(rows):
""" round up to the nearest 20, then divide by 20
eg 105 rounds to 120 then divides by 20 to returns 6"""
return (rows - rows % -20) / 20 |
def join_url(*parts):
"""join parts of URL into complete url"""
return '/'.join(str(s).strip('/') for s in parts) |
def is_list_having_non_empty_items(list1):
"""
If the list has items, and if any of them is not empty/None, returns True.
Otherwise, False.
If the list has no elements, it returns False.
If the list has elements but they are empty/None, return False.
"""
result = False
if not list1:
return result
found = False
for item in list1:
if item:
found = True
break
return found |
def width(text, width):
"""
Insert a new line character for each block of `width` characters into the
input text.
:param str text: the input text for newlining.
:param int width: a positive integer for dividing input with new lines.
:returns: the newlined text.
"""
if not isinstance(width, int) or width < 1:
return text
if not isinstance(text, str):
return None
text_segments = [text[i:i+width] for i in range(0, len(text), width)]
return '\n'.join(text_segments) |
def poorly_spaced_path(lam):
"""lam in [0,1] -> (offset in [0, 4], force_constant in [1, 16])"""
lam_eff = lam ** 4
offset = 4 * lam_eff
force_constant = 2 ** (4 * lam_eff)
return offset, force_constant |
def surround_quotes(obj):
"""
Surround input (string)
with double quotes.
"""
# add double quotes around string
obj = '"' + obj + '"'
# return quoted string
return obj |
def populate_set(line, val_set):
"""
Collects values and put it in a set
"""
pos = line.find("\"")
pos1 = line.rfind("\"")
sub = line[pos + 1:pos1]
val_list = sub.split(',')
for val in val_list:
val_set.add(float(val.strip()))
return val_set |
def DoSlash(sDirName):
"""Add a tailing slash if missing.
"""
return sDirName if sDirName[-1]=="/" else sDirName+"/" |
def nullcnt(xs):
"""Counts null values in Graphite query result"""
return len([x for x in xs if x is None]) |
def _get_subword_units(token, gram):
"""Return subword-units presentation, given a word/token.
"""
if token == '</s>': # special token for padding purpose.
return [token]
t = '#' + token + '#'
return [t[i:i + gram] for i in range(0, len(t) - gram + 1)] |
def cdr_to_stage(score):
"""
Convert the Clinical Dementia Rating scale (CDR) to descriptive terms (O'Bryant et al., 2010).
This can be helpful for qualitative purposes.
"""
if score == 0.0:
return ('Normal')
elif score == 0.5:
return ('Questionable')
elif score == 1.0:
return ('Mild')
elif score == 2.0:
return ('Moderate')
elif score == 3.0:
return ('Severe')
else:
return ('NaN') |
def _split_regex(regex):
"""
Return an array of the URL split at each regex match like (?P<id>[\d]+)
Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/']
"""
if regex[0] == '^':
regex = regex[1:]
if regex[-1] == '$':
regex = regex[0:-1]
results = []
line = ''
for c in regex:
if c == '(':
results.append(line)
line = ''
elif c == ')':
line = ''
else:
line = line + c
if len(line) > 0:
results.append(line)
return results |
def umm_fields(item):
"""Return only the UMM part of the data"""
if 'umm' in item:
return item['umm']
return item |
def calc_active_stake(staking_balance, deposit_cap, frozen_deposits_percentage=10):
"""
>>> full_balance = 1000
>>> calc_active_stake(9000, full_balance)
9000.0
>>> calc_active_stake(12000, full_balance)
10000.0
>>> calc_active_stake(9000, 400)
4000.0
>>> calc_active_stake(12000, 400)
4000.0
"""
return min(float(staking_balance), deposit_cap * 100 / frozen_deposits_percentage) |
def longest_common_subsequence_memoization(X, Y, m, n, dp):
"""
:param X: String 1st
:param Y: String 2nc
:param m: length of String 1
:param n: length of String 2
:param dp: Array for Storage of The Pre Calculate Value
:return: length of Common Subsequence
"""
"""
>>> longest_common_subsequence_memoization("programming", "gaming")
6
>>> longest_common_subsequence_memoization("physics", "smartphone")
2
>>> longest_common_subsequence_memoization("computer", "food")
1
"""
# base case
if m == 0 or n == 0:
return 0
# if the same state has already been
# computed
if dp[m - 1][n - 1] != -1:
return dp[m - 1][n - 1]
# if equal, then we store the value of the
# function call
if X[m - 1] == Y[n - 1]:
# store it in arr to avoid further repetitive
# work in future function calls
dp[m - 1][n - 1] = 1 + longest_common_subsequence_memoization(
X, Y, m - 1, n - 1, dp
)
return dp[m - 1][n - 1]
else:
# store it in arr to avoid further repetitive
# work in future function calls
dp[m - 1][n - 1] = max(
longest_common_subsequence_memoization(X, Y, m, n - 1, dp),
longest_common_subsequence_memoization(X, Y, m - 1, n, dp),
)
return dp[m - 1][n - 1] |
def _create_weights_tuple(weights):
"""
Returns a tuple with the weights provided. If a number is provided,
this is converted to a tuple with one single element.
If None is provided, this is converted to the tuple (1.,)
"""
import numbers
if weights is None:
weights_tuple = (1.,)
elif isinstance(weights,numbers.Number):
weights_tuple = (weights,)
else:
weights_tuple = tuple(float(i) for i in weights)
return weights_tuple |
def gen_names_for_range(N, prefix="", start=1):
"""generates a range of IDS with leading zeros so sorting will be ok"""
n_leading_zeros = len(str(N))
format_int = prefix + "{:0" + str(n_leading_zeros) + "d}"
return [format_int.format(i) for i in range(start, N + start)] |
def strip_account_url(account_url):
"""
Remove http/https for an URL
"""
if account_url:
if 'https://' in account_url:
account_url = account_url.split('https://')[1]
elif 'http://' in account_url:
account_url = account_url.split('http://')[1]
return account_url |
def deref_or_none(dictionary, key):
"""
@brief Look up a key in a dict; return None if not found
"""
if not dictionary:
return None
if key in dictionary.keys():
return dictionary[key]
else:
return None |
def bool_(input_):
""" Convert boolean or string to boolean, also 'False' and 'F' to False """
return bool(input_) if input_.upper() not in ["FALSE", "F"] else False |
def get_default_params_bps_par():
"""Return a tuple containing the default velocity perturbation parameters
given in :cite:`BPS2006` for the parallel component."""
return (10.88, 0.23, -7.68) |
def get_list_type(param_type):
"""
return type of given list
"""
if str(param_type).find('[str]') != -1:
return str
if str(param_type).find('[int]') != -1:
return int
if str(param_type).find('[float]') != -1:
return float
if str(param_type).find('[bool]') != -1:
return bool
return str |
def unicode_to_str(value):
"""If python2, returns unicode as a utf8 str"""
if type(value) is not str and isinstance(value, type(u"")):
value = value.encode("utf8")
return value |
def argparse_bool(s):
"""
parse the string s to boolean for argparse
:param s:
:return: bool or None by default
example usage: parser.add_argument("--train", help="train (finetune) the model or not", type=mzutils.argparse_bool, default=True)
"""
if not isinstance(s, str):
return s
if s.lower() in ('yes', 'y', 't', 'true', 1):
return True
elif s.lower() in ('no', 'n', 'f', 'false', 0):
return False
else:
return None |
def input_to_int(usr_input):
"""
Testuje zda-li uzivatelem zadany vstup je cislo. Pokud ano vraci ho.
:param usr_input: uzivatelsky vstup
:return: uzyivatelsky vstu prevedeny na int, v pripade neuspechu -1
"""
try:
value = int(usr_input)
except ValueError:
return -1
if value <= 0:
return -1
return value |
def parse_default_value(default_value,
value_type,
recognized_types=('Bool', 'DecDouble')):
""" Parses default_value string to actual usable C++ expression.
@param default_value_str: default_value field specified in document_policy_features.json5
@param value_type: value_type field specified in document_policy_features.json5
@param recognized_types: types that are valid for value_type
@returns: a C++ expression that has type mojom::PolicyValue
"""
if (value_type not in recognized_types):
raise ValueError("{} is not recognized as valid value_type({})".format(
value_type, recognized_types))
policy_value_type = "mojom::PolicyValueType::k{}".format(value_type)
if default_value == 'max':
return "PolicyValue::CreateMaxPolicyValue({})".format(
policy_value_type)
if default_value == 'min':
return "PolicyValue::CreateMinPolicyValue({})".format(
policy_value_type)
return "PolicyValue::Create{}({})".format(value_type, default_value) |
def conv_str_to_bool(text, mapping_dict=None):
"""
Map a text to a boolean value.
The default text to bool mapping is provided in the
default_map dict below, however text
and mapping_dict as inputs to map as per needs.
default_map = {'yes': True, 'y': True, 'no': False, 'n': False }
"""
default_map = {'yes': True,
'y': True,
'no': False,
'n': False
}
mapping = mapping_dict if mapping_dict else default_map
result = mapping.get(text.lower(), False)
return result |
def sec_to_time(seconds):
"""Transform seconds into a formatted time string.
Parameters
-----------
seconds : int
Seconds to be transformed.
Returns
-----------
time : string
A well formatted time string.
"""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "%02d:%02d:%02d" % (h, m, s) |
def check_prime(number) -> bool:
"""
:param number: Number
:return: bool (True/False)
"""
if number <= 1:
return False
if number <= 3:
return True
if number % 2 == 0 and number % 3 == 0:
return False
i = 5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i = i + 6
return True |
def power(x,p):
""" Elevates the number x to the power p.
Arguments:
----------
* x [int/float]: a number.
* p [int]: the power that will elevate x.
Return:
-------
* res [int/float]: result of x**p
Why?:
-----
According to the project pdf, the only authhorized operations
are '+','-','*' and '/'
"""
i = 1
if p == 0:
return 1
res = x
while i < p:
res *= x
i += 1
return res |
def get_chapter_number(verse_id: int) -> int:
"""
Given a verse id return the int chapter number.
:param verse_id:
:return: int chapter number
"""
return int(verse_id % 1000000 / 1000) |
def perm_recursive(S):
"""
Return a list with all permutations of the iterable passed as argument.
Uses the simple recursive solution. This Algorithm does not handle repeated elements well.
"""
def expand_inserting(c, L):
return [L[0:i] + [c] + L[i:] for i in range(len(L) + 1)]
if not isinstance(S, list):
S = list(S) # to handle strings
if len(S) == 0:
return []
elif len(S) == 1:
return [S]
c, L = S[0], S[1:]
res = []
for newL in perm_recursive(L):
res.extend(expand_inserting(c, newL))
return res |
def save_split(s, sep, maxsplit):
"""Split string, always returning n-tuple (filled with None if necessary)."""
tok = s.split(sep, maxsplit)
while len(tok) <= maxsplit:
tok.append(None)
return tok |
def majorToLNames(thisMajor,listOfStudents):
"""
return a list of the last names of students with the major, thisMajor
>>> majorToLNames("MATH",[Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")])
['KAY']
>>>
"""
answerList = []
for student in listOfStudents:
# step through every item in listOfStudents
# when you find a match, return that students's major
if student.major == thisMajor:
answerList.append(student.lName)
# if you got all the way through the loop and didn't find
# the name, return False
return answerList |
def group(merge_func, tokens):
"""
Group together those of the tokens for which the merge function returns
true. The merge function should accept two arguments/tokens and should
return a boolean indicating whether the strings should be merged or not.
Helper for tokenise(string, ..).
"""
output = []
if tokens:
output.append(tokens[0])
for token in tokens[1:]:
prev_token = output[-1]
if merge_func(prev_token, token):
output[-1] += token
else:
output.append(token)
return output |
def filePathToSafeString(filePath):
"""
Returns string representation of a given filepath safe for a single filename usage
>>> filePathToSafeString('C:/Windows/system32')
'C__Windows_system32'
"""
retVal = filePath.replace("/", "_").replace("\\", "_")
retVal = retVal.replace(" ", "_").replace(":", "_")
return retVal |
def is_power_of_two(input_integer):
""" Test if an integer is a power of two. """
if input_integer == 1:
return False
return input_integer != 0 and ((input_integer & (input_integer - 1)) == 0) |
def describe_list_indices(full_list):
"""
Describe the indices of the given list.
Parameters
----------
full_list : list
The list of items to order.
Returns
-------
unique_elements : list
A list of the unique elements of the list, in the order in which
they first appear.
element_indices : dict
A dictionary of lists for each unique element, giving all the
indices in which they appear in the original list.
"""
unique_elements = []
element_indices = {}
for i in range(len(full_list)):
item = full_list[i]
# new item
if item not in unique_elements:
unique_elements.append(item)
element_indices[item] = [i]
# previously seen item
else:
element_indices[item].append(i)
return unique_elements, element_indices |
def get_survived_value(x):
""" returns the int value for the nominal value survived
:param x: a value that is either 'yes' or 'no'
:return: returns 1 if x is yes, or 0 if x is no
"""
if x == 'yes':
return 1
else:
return 0 |
def quarter_for_month(month):
"""return quarter for month"""
if month not in range(1, 13):
raise ValueError('invalid month')
return {1: 1, 2: 1, 3: 1,
4: 2, 5: 2, 6: 2,
7: 3, 8: 3, 9: 3,
10: 4, 11: 4, 12: 4}[month]
# return (month + 2) // 3 |
def fib(n: int) -> int:
"""
:param n: input integer
:return: Nth number of fibonacci sequence
Time complexity : O(2^n)
Space complexity : O(n)
"""
if n <= 2:
return 1
return fib(n - 1) + fib(n - 2) |
def group_by(iterable, key_selector):
"""
Returns an iterator which groups the iterable with a key provided by the
supplied function. The source iterable does not need to be sorted.
:param iterable: The items over which to iterate.
:param key_selector: A function which selects the key to group on.
:return: A tuple of the key and the list of items matching the key.
"""
groups = {}
for item in iterable:
key = key_selector(item)
if key in groups:
groups[key].append(item)
else:
groups[key] = [item]
return groups |
def restructure_gene_info(allele_annotations):
"""Restructure information related to gene
"""
gene_data = []
assembly_annotation = allele_annotations[0].get('assembly_annotation')
if assembly_annotation and assembly_annotation[0]:
for _doc in assembly_annotation[0].get('genes'):
if _doc:
if "orientation" in _doc:
_doc['strand'] = _doc.pop("orientation")
if _doc["strand"] == "plus":
_doc["strand"] = "+"
elif _doc["strand"] == "minus":
_doc["strand"] = "-"
_doc['geneid'] = _doc.pop('id')
_doc['symbol'] = _doc.pop('locus')
_doc['so'] = _doc.pop('sequence_ontology')
for _item in _doc['rnas']:
if _item:
_item['refseq'] = _item.pop('id')
_item['so'] = _item.pop('sequence_ontology')
if 'product_id' in _item:
_item['protein_product'] = {'refseq': None}
_item['protein_product']['refseq'] = _item.pop('product_id')
gene_data.append(_doc)
return gene_data |
def insertNewlines(text, lineLength):
"""
Given text and a desired line length, wrap the text as a typewriter would.
Insert a newline character ("\n") after each word that reaches or exceeds
the desired line length.
text: a string containing the text to wrap.
line_length: the number of characters to include on a line before wrapping
the next word.
returns: a string, with newline characters inserted appropriately.
"""
if len(text) < lineLength:
return text
chunk = text[0:lineLength]
return chunk + "\n" + insertNewlines(text[lineLength:], lineLength) |
def partition(alist, indices):
"""A function to split a list based on item indices
Parameters:
-----------------------------
: alist (list): a list to be split
: indices (list): list of indices on which to divide the input list
Returns:
-----------------------------
: splits (list): a list of subreads based on cut sites
"""
return [alist[i:j] for i, j in zip([0]+indices, indices+[None])] |
def r(out, target, std_deviation, daily_return):
"""
Calculates a term that is used more often
:param out: output from model
:param target: target returns (annual)
:param std_deviation: volatility estimate
:param daily_return: daily returns for each time step
:return:
"""
return out * target / std_deviation * daily_return |
def calc_recall(TP, FN):
"""
Calculate recall from TP and FN
"""
if TP + FN != 0:
recall = TP / (TP + FN)
else:
recall = 0
return recall |
def HumanizeBytes(totalBytes, precision=1, suffix=None):
"""
Convert a number of bytes into the appropriate pretty kiB, MiB, etc.
Args:
totalBytes: the number to convert
precision: how many decimal numbers of precision to preserve
suffix: use this suffix (kiB, MiB, etc.) instead of automatically determining it
Returns:
The prettified string version of the input
"""
if (totalBytes == None):
return "0 B"
converted = float(totalBytes)
suffix_index = 0
suffix_list = ['B', 'kiB', 'MiB', 'GiB', 'TiB']
while (abs(converted) >= 1000):
converted /= 1024.0
suffix_index += 1
if suffix_list[suffix_index] == suffix:
break
return "{0:.{1}f} {2}".format(converted, precision, suffix_list[suffix_index]) |
def translate(x1, x2):
"""Translates x2 by x1.
Parameters
----------
x1 : float
x2 : float
Returns
-------
x2 : float
"""
x2 += x1
return x2 |
def _ExtractBertThroughput(output):
"""Extract throughput from Horovod output.
Args:
output: Horovod output
Returns:
A tuple of:
Average throughput in sentences per second (float)
Unit of the throughput metric (str)
"""
# Start from last line and iterate backwards.
avg_throughput = 0
for line in output.splitlines()[::-1]:
if 'Throughput Average (sentences/sec) =' in line:
split_line = line.split()
avg_throughput = float(split_line[-1])
break
return round(avg_throughput, 1), 'sentences/second' |
def get_offset(num, rows, spacing):
"""Return offset from prototype position.
Positional arguments:
num -- the number of the object, starting from 0
rows -- how many rows before wrapping
spacing -- a tuple of (x,y) spaing between objects
"""
x_offset = (num % rows) * spacing[0] # x-spacing
y_offset = (num // rows) * spacing[1] # y-spacing
return (x_offset, y_offset) |
def generate_time_str(time):
"""convert time (in seconds) to a text string"""
hours = int(time // 60**2)
minutes = int((time - hours*60**2) // 60)
seconds = int((time - hours*60**2 - minutes*60) // 1)
ret = ''
if hours:
unit = 'hr' if hours == 1 else 'hrs'
ret += f'{hours} {unit} '
if minutes:
unit = 'min' if minutes == 1 else 'mins'
ret += f'{minutes} {unit} '
if not (hours and minutes):
unit = 'sec' if seconds == 1 else 'secs'
ret += f'{seconds} {unit}'
return ret.strip() |
def cnf_sat(clauses):
"""
returns true if clauses is satisfied
"""
return len(clauses) == 0 |
def unquote(s):
"""Strip single quotes from the string.
:param s: string to remove quotes from
:return: string with quotes removed
"""
return s.strip("'") |
def turn(orientation, direction):
"""Given an orientation on the compass
and a direction ("L" or "R"), return a
a new orientation after turning 90 deg
in the specified direction."""
compass = ['N', 'E', 'S', 'W']
if orientation not in compass:
raise ValueError('orientation must be N, E, S, or W')
if direction not in ['R', 'L']:
raise ValueError('direction must be R or L')
i = (compass.index(orientation) + (1 if direction == 'R' else -1)) % len(compass)
return compass[i] |
def _map_features(features, support):
"""Map old features indices to new ones using boolean mask."""
feature_mapping = {}
new_idx = 0
for (old_idx, supported) in enumerate(support):
if supported:
val = new_idx
new_idx += 1
else:
val = None
feature_mapping[old_idx] = val
new_features = []
for feature in features:
new_feature = feature_mapping[feature]
if new_feature is not None:
new_features.append(new_feature)
return new_features |
def constraintsHAngles(bonds):
"""Given a set of bonds from a Topology, return the set of angle constraints that
you expect to appear in the system. An angle is constrained if the bond sequence
is H-O-X or H-X-H where X is any element.
"""
expected_constraint_set = set()
for bond in bonds:
if bond[0].element.symbol=='H' and bond[1].element.symbol=='O':
indexH = bond[0].index
indexO = bond[1].index
for bond2 in bonds:
if bond2[0].index==indexO and bond2[1].index!=indexH:
expected_constraint_set.add(tuple(sorted([indexH, bond2[1].index])))
elif bond2[1].index==indexO and bond2[0].index!=indexH:
expected_constraint_set.add(tuple(sorted([indexH, bond2[0].index])))
elif bond[1].element.symbol=='H' and bond[0].element.symbol=='O':
indexH = bond[1].index
indexO = bond[0].index
for bond2 in bonds:
if bond2[0].index==indexO and bond2[1].index!=indexH:
expected_constraint_set.add(tuple(sorted([indexH, bond2[1].index])))
elif bond2[1].index==indexO and bond2[0].index!=indexH:
expected_constraint_set.add(tuple(sorted([indexH, bond2[0].index])))
elif bond[0].element.symbol=='H' and bond[1].element.symbol!='O':
indexH = bond[0].index
indexX = bond[1].index
for bond2 in bonds:
if bond2[0].index==indexX and (bond2[1].index!=indexH
and bond2[1].element.symbol=='H'):
expected_constraint_set.add(tuple(sorted([indexH, bond2[1].index])))
elif bond2[1].index==indexX and (bond2[0].index!=indexH
and bond2[0].element.symbol=='H'):
expected_constraint_set.add(tuple(sorted([indexH, bond2[0].index])))
elif bond[1].element.symbol=='H' and bond[0].element.symbol!='O':
indexH = bond[1].index
indexX = bond[0].index
for bond2 in bonds:
if bond2[0].index==indexX and (bond2[1].index!=indexH
and bond2[1].element.symbol=='H'):
expected_constraint_set.add(tuple(sorted([indexH, bond2[1].index])))
elif bond2[1].index==indexX and (bond2[0].index!=indexH
and bond2[0].element.symbol=='H'):
expected_constraint_set.add(tuple(sorted([indexH, bond2[0].index])))
return expected_constraint_set |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.