content stringlengths 42 6.51k |
|---|
def wait_duration(attempt):
""" Calculate the wait time based on the number of past attempts.
The time grows exponentially with the attempts up to a maximum
of 10 seconds.
Args:
attempt: Current count of reconnection attempts.
Returns:
int: The number of seconds to wait before next a... |
def calculateSubstringsLengthK(s, k):
"""
Return substrings of size k in s
"""
substrings, index = [], 0
while index + k <= len(s):
substrings.append(s[index : index + k])
index += k
return substrings |
def calculate_thermal_diffusivity(thermal_conductivity, density, specific_heat_capacity):
"""
Returns thermal diffusivity from thermal conductivity.
alpha = k/(rho*c_p)
:param thermal_conductivity:
:param density:
:param specific_heat_capacity:
:return:
"""
diffusivity = thermal_cond... |
def from_pixel(x, y, n):
"""Converts a NxN pixel position to a (-1..1, -1..1) complex number."""
return complex(2.0 * x / n - 1.0, 2.0 * y / n - 1.0) |
def check_parallel_results(results, op):
"""Function used to check the results of run_parallel.
NOTE: This function was originally located in the shell module of
swift_build_support and should eventually be replaced with a better
parallel implementation.
"""
fail_count = 0
if results is No... |
def build_subtree(node, deps, known_nodes=None):
"""Build the deps subtree of a given task."""
if known_nodes is None:
known_nodes = set()
subtree = {}
known_nodes.add(node)
for t in deps[node]:
if t not in known_nodes:
subtree[t] = {}
known_nodes.add(t)
f... |
def upper(value): # Only one argument.
"""Converts a string into all lowercase
How to Use
{{ value|lower|lower|.... }}
"""
return value.upper() |
def subclasses(cls):
"""Get all child classes of `cls` not including `cls`, transitively."""
assert isinstance(cls, type), "cls is not a class, type: {}".format(
type(cls)
)
children = set(cls.__subclasses__())
return children.union(*map(subclasses, children)) |
def wrap_tuple(unwrapped):
""" Wraps any non-tuple types in a tuple """
return (unwrapped if isinstance(unwrapped, tuple) else (unwrapped,)) |
def make_anagram_1(a, b):
"""Using a dictionary: O(n_a+n_b) time"""
count_dict = {}
for n in a:
if n in count_dict.keys():
count_dict[n] +=1
else:
count_dict[n] = 1
for n in b:
if n in count_dict.keys():
count_dict[n] -=1
else:
... |
def create_points_for_rectangle(x, y, width, height):
"""Simple helper function to create points for a rectangle
Arguments:
x {int} -- [description]
y {int} -- [description]
width {int} -- [description]
height {int} -- [description]
Returns:
[int] ... |
def opposite_sub_simplex(simplex, sub_simplex):
"""
Get the opposite sub simplex of a given sub simplex in a simplex.
The opposite sub simplex of a sub simplex f in a simplex T is the simplex consisting of all the vertices
of T not in f.
:param simplex: Simplex defined by a list of vertex indices.... |
def count_ways_recursive(n: int, m: int) -> int:
"""
"""
if n == 0 or m == 0:
return 0
if n == 1 or m == 1:
return 1
return count_ways_recursive(n - 1, m) + count_ways_recursive(n, m - 1) |
def coord_map_forward_1d(coord, x_step = 1, x_shift = 0, mode = 'linear'):
""" Maps input coordinate (1D, value) to output coordinate given
parameters step (m) and shift (b) for linear transformation
y = m * x + b
Intended to map meshgrid output arrays back to spatial coordinates.
"""
... |
def isJob(obj):
"""Returns true of the object is a job, false if not
@return: If the object is a job
@rtype: bool"""
return obj.__class__.__name__ in ["Job", "NestedJob"] |
def get_value_from_json(json_dict, sensor_type, group, tool):
"""Return the value for sensor_type from the JSON."""
if group not in json_dict:
return None
if sensor_type in json_dict[group]:
if sensor_type == "target" and json_dict[sensor_type] is None:
return 0
return j... |
def expose_header(header, response):
"""
Add a header name to Access-Control-Expose-Headers to allow client code to access that header's value
"""
exposedHeaders = response.get('Access-Control-Expose-Headers', '')
exposedHeaders += f', {header}' if exposedHeaders else header
response['Access-Con... |
def plural(word, count=2):
""" Return the plural version the word if there is more than one count, otherwise return as is."""
if count > 1:
if word.endswith('sh'):
return word + 'es'
else:
return word + 's'
else:
return word |
def split_into_chunks(lista, split_dims):
"""
Split a list into evenly sized chunks. The last chunk will be smaller if the
original list length is not divisible by 'split_dims'.
:param lista: List to be split.
:param split_dims: Length of each split chunk.
"""
aux_list = []
# For item i in a ra... |
def least_significant_digit(number):
"""Find out how many digits of precision a number has.
Parameters
----------
number: float
The number.
"""
number_string = str(number)
if ('.' in number_string):
print(number_string)
print(number_string.partition('.'))
pri... |
def normalise(value: float, current_min: float, current_max: float, intended_min: float, intended_max: float) -> float:
"""
Function used to normalise a value to fit within a given range, knowing its actual range.
Uses standard MinMax normalisation.
:param value: Value to be normalised
:param curr... |
def frame_error_rate_calculation(n_suc, n_tot):
"""
Calculates the frame error rate given a success rate from the decoding stage. If no frame was successfully decoded,
the protocol is aborted.
:param n_suc: The number of frames that was successfully decoded.
:param n_tot: The total number of frames.... |
def get_or_default(mapping, key, default_func=lambda: 'UNK'):
"""Get a key or call a func if not found in dict
Notes:
- UNK = unknown
"""
try:
return mapping[key]
except KeyError:
return default_func() |
def overlap(start1, end1, start2, end2):
"""Does the range (start1, end1) overlap with (start2, end2)?"""
# https://nedbatchelder.com/blog/201310/range_overlap_in_two_compares.html
if start1 > end1:
start1, end1 = end1, start1
if start2 > end2:
start2, end2 = end2, start2
return end1... |
def is_leap(year):
"""Returns True iff the given year number represents a leap year."""
return year % 400 == 0 or(year % 4 == 0 and year % 400 != 0) |
def get_domain_from_fqdn(url: str) -> str:
"""Input a fqdn and get only the domain name back
Arguments:
url STR -- url string of a domain. Eg. http://stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url
Returns:
STR -- domain name in str format. Eg. stackover... |
def cdp_file_output(in_seq_name1, in_seq_name2, ref, nt, ext):
"""
Generate output file name
:param in_seq_name1: sample name/s (str)
:param in_seq_name2: sample name/s (str)
:param ref: reference name (str)
:param nt: aligned read length (int)
:param ext: extension (ie. csv or pdf)
:ret... |
def escape_decode(data, errors='strict'):
"""None
"""
l = len(data)
i = 0
res = []
while i < l:
if data[i] == '\\':
i += 1
if i >= l:
raise ValueError("Trailing \\ in string")
else:
if data[i] == '\\':
... |
def all_conditions_nominal(conditions):
"""
Checks whether all conditions are nominal
If no conditions are specified, assume nominal
"""
if not conditions:
return True
return all([c.nominal for c in conditions]) |
def flatten_config(config, sep='--', prefix=None):
"""
>>> flatten_config({'a': 1, 'b': {'c': {'d': 4, 'e': [5, 6]}}})
{'a': 1, 'b--c--d': 4, 'b--c--e': [5, 6]}
"""
result = {}
for key, value in config.items():
key = key if prefix is None else f'{prefix}{sep}{key}'
if isinstance(... |
def chain_to_quadratic(chain, target_adjacency, chain_strength):
"""Determine the quadratic biases that induce the given chain.
Args:
chain (set/list/tuple):
The variables that make up a chain.
target_adjacency (dict/:class:`networkx.Graph`):
The adjacency dict of the t... |
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
"""Reimplementation of math.isclose() as it does not exist in Micropython."""
return abs(a-b) <= max( rel_tol * max(abs(a), abs(b)), abs_tol ) |
def help(title, url=None) -> str:
"""Creat help badge
Args:
title: help text
url: url to open in new tab (optional)
Returns:
HTML formatted help badge
"""
if url is not None:
return f'<a title="{title}" href="{url}" target="_blank"><span class="badge pull-right" sty... |
def get_lost_guesses(guessed_letter, secret_word):
"""
Calculates the number of guesses lost from a guess according to
the secret_word.
:param guessed_letter: The letter the player guessed.
:type guessed_letter: str
:param secret_word: The secret word that the player needs to guess.
:type s... |
def get_translated(translation, lang=None):
"""Get a specific translation from a TranslatedString."""
# If we don't find the requested language, return this
lang = lang or "EN"
if not translation:
# If empty, return.
return None
for t in translation:
if t.language == lang:
... |
def validate_scale_factors(value, _):
"""Validate the `validate_scale_factors` input."""
if value and len(value) < 3:
return 'need at least 3 scaling factors.' |
def gasKgKgDryToMoist(q,qh2o):
"""
Take Kg/Kg dry air to Kg/Kg moist air.
"""
r = q/(1+qh2o)
return r |
def sub(a, b):
""" Subtrahiert die beiden Matrizen a, b komponentenweise.
Gibt das Resultat der Subtraktion als neue Matrix c aus. """
n = len(a)
c = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
c[i][j] = a[i][j] - b[i][j]
return c |
def remove_indent(s):
"""Remove indention of paragraph."""
s = "\n".join(i.lstrip() for i in s.splitlines())
return s |
def get_totals(path_sha_loc):
"""Returns: total numbers of files, commits, LoC for files in `path_sha_loc`
"""
all_commits = set()
total_loc = 0
for sha_loc in path_sha_loc.values():
all_commits.update(sha_loc.keys())
total_loc += sum(sha_loc.values())
return len(path_sha_loc), ... |
def _transform_volumes(volumes):
"""Transform volume mapping from list to dict regconized by docker lib
"""
dict_volume = {}
for volume in volumes:
# Example format:
# /var/tmp:/dest_var_tmp:rw => {
# /var/tmp': {
# 'bind': '/dest_var_tmp',
# ... |
def _ismissing(val):
"""Return True if a value is None, greater than 90.0, or less than -90.
This function is used to check for invalid latitude values.
Args:
val (numeric): A numeric value.
Returns:
:obj:`bool`: True if the value is None, greater than 90.0, ... |
def makeSortedGlyphLists(glyphList, fdGlyphDict):
"""
Returns a list containing lists of glyph names (one for each FDDict).
glyphList: list of all glyph names in the font
fdGlyphDict: {'a': [2, 1], 'negative': [1, 2], '.notdef': [0, 0]}
keys: glyph names
values: [FDDi... |
def urlify(string):
"""
replace spaces with '+'
"""
string = string.strip()
return string.replace(' ', '+') |
def kilometers_to_miles(km):
"""
Convert from units of kilometers to miles
PARAMETERS
----------
km: float
A distance value in units of kilometers
RETURNS
-------
miles: float
A distance value in units of miles
"""
#convert km to miles:
return km*0.621371 |
def _get_tensor_name(node_name, output_slot):
"""Get tensor name given node name and output slot index.
Parameters
----------
node_name : str
Name of the node that outputs the tensor, as a string.
output_slot : str
Output slot index of the tensor, as an integer.
Returns
--... |
def remove_puncatuation(review_str:str)->str:
"""remove puncatuation of a string
"""
import re
return re.sub(r'[^\w\s]', '', review_str) |
def num_mapper(nums, suggested_num_chunks):
"""
text: to be divided
suggested_num_chunks: suggested number of chunks
typically equal to num of cores
"""
chunk_size = max(len(nums) // suggested_num_chunks, 1)
return [nums[i:i+chunk_size] for i in range(0, len(nums), ch... |
def removelatex(string):
"""
Remove the latex $ symbols from a unit string
Parameters
----------
string : str
String containing latex math mode $ delimiters
Returns
-------
string : str
Input string with $ delimiters removed
"""
if '$' in string:
string ... |
def flatten(stack, separator='-', prefix=''):
""" Will return a one-level dictionary of all stack keys
seperated by '-' matched to their concluding value.
Example: data_key-data-no_filter-x_key-y_key-view_key : View.View
(This is straight from stackoverflow.com)
"""
return {prefix + separator + ... |
def is_power2(num):
"""Check if is a power of 2."""
return num != 0 and ((num & (num - 1)) == 0) |
def get_column_ids():
"""Get a list of log file column ids."""
columns_ids = [
'T_experiment', 'T_loop', 'received', 'sent', 'lost', 'relative_loss',
'data_received', 'latency_min (ms)', 'latency_max (ms)',
'latency_mean (ms)', 'latency_variance (ms)', 'pub_loop_res_min (ms)',
'p... |
def string_of_items(dic):
"""
Return a string containing all keys of a dictionary, separated by a comma
(Helper function for structure inlining)
:param dic: dictionary [key=string: value=string]
:return: string constructed of the dictionaries' keys
"""
s = ''
for k, v in dic.items():
... |
def str_cvt_upper(s):
"""konversi kecil->besar"""
return s.upper() |
def worker_to_cmd(is_gpu: bool, worker: int) -> str:
"""Returns a the bash command to run a worker job.
Args:
is_gpu (bool): True if worker is a gpu worker false if cpu worker
worker (int): The worker id, this is the GPU id for gpu workers
Returns:
A string containing the bash comm... |
def calculate_time(time_sec):
"""convert time in secs to days hours minutes and seconds"""
days = time_sec // (3600 * 24)
hours = time_sec % (3600 * 24) // 3600
minutes = time_sec % 3600 // 60
seconds = time_sec % 60
return ('{} days {} hours {} minutes {} seconds'.format(int(days),int(hou... |
def calculate_EMA(prev_EMA, price, multiplier):
"""
Returning the EMA for t time
"""
return (price - prev_EMA) * multiplier + prev_EMA |
def str_artists(artists):
"""Generate a pretty string from multiple artists (a list) from Spotify."""
artist_string = ''
for artist in artists:
artist_string += artist["name"] + ', '
artist_string = artist_string.rstrip(', ')
return artist_string |
def relu(x):
"""
ReLU activation function
"""
return x * (x > 0) |
def city_info(request):
"""Return an OpenWeatherMap API city location."""
return {
'_id': 6434841,
'name': 'Montcuq',
'country': 'FR',
'zip_code': 46800,
'coord': {
'lon': 1.21667,
'lat': 44.333328
}
} |
def _get_rule_delta_code_comment(
delta_seconds: int,
scope: str,
) -> str:
"""Create the comment that explains how the ZoneRule delta_code[_encoded]
was calculated.
"""
delta_minutes = delta_seconds // 60
if scope == 'extended':
return f"(deltaMinutes={delta_minutes})/15 + 4"
el... |
def mapping_given(a1, a2, b1, b2):
"""Returns function to translate b's coords to a's coords, assuming a1=b1 and a2=b2."""
# How do we translate the line between b1->b2 into a1->a2 style?
adiff = [y - x for x, y in zip(a1, a2)]
bdiff = [y - x for x, y in zip(b1, b2)]
if 3 != len(set([abs(ad) for ad... |
def _unpack_field(examples, field):
"""Get all values of examples under the specified field.
Parameters
----------
examples : iterable
An iterable of objects.
field : str
The field for value retrieval.
Returns
-------
list
A list of values.
"""
return [e... |
def remove_last_entry_from_path(
path: str):
"""
- Use this to remove the last entry from a path.
:param path: Initial path.
:return: New path with the last entry removed.
"""
splitted = path.split('/')
new_path = ''
for index in range(len(splitted) - 1):
new_path += ... |
def get_flood_risk_rating(num):
"""Converts an integer value of a flood risk rating to the rating it
represents - low (0/1), moderate (2), high (3), severe (4)"""
if num == 0 or num == 1:
return "Low"
if num == 2:
return "Moderate"
if num == 3:
return "High"
if num == 4... |
def parse_hosts(hosts):
"""
Parses a comma delimited string of hosts.
Ex. localhost:9200,localhost:9201,localhost:9202
:param str hosts The hosts string.
:return List An Elasticsearch list of hosts.
"""
return hosts.split(',') |
def _curve_data_extrator_time(sigObjs):
"""
Extracts data from all curves from each SignalObj.
Parameter (default), (type):
-----------------------------
* sigObj (), (list):
a list with SignalObjs for curve data extraction
Return (type):
--------------
* curveDat... |
def find_indexes(lst, item):
"""Find the index of a character (or characters) in a list"""
start_at = -1
locs = []
while True:
try:
loc = lst.index(item, start_at + 1)
except ValueError:
break
else:
locs.append(loc)
start_at = loc
... |
def convert_dir_regex_to_dir_prefix_regex(dir_regex):
"""
The patterns used to match directory names (and file names) are allowed
to match a prefix of the name. This 'feature' was unintentional, but is
being retained for compatibility.
This means that a regex that matches a directory name can't be... |
def can_combine(element1, element2):
""" Return True if elements e1 and e2 can be combined per the rules of the game. """
if element1 > element2:
element1, element2 = element2, element1
if 1 <= element1 <= 5:
return element1 == element2 or element2 == 5
if element1 == 6:
return ... |
def conv(value, detectlimit):
"""Convert a value into something that gets returned"""
# Careful here, we need to keep missing values for a later replacement
if value is None or value == "":
return None
if value in ["n/a", "did not collect"]:
return None
if value.startswith("<"):
... |
def get_rounds(number):
"""
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
num_list = [number, (number+1), (number+2)]
return num_list |
def bulk_structural_analysis(class_name, list, x) :
"""
@param list : a list of tuple (class function name, class function description)
@rtype : a list of strings related to the findings
"""
formatted_str = []
for method_name, description in list :
structural_analysis_results = x.tainted_packages.search_m... |
def my_sum1(n):
"""
>>> my_sum1(10)
55.0
"""
return (1/2)*n*(n + 1) |
def macTolist(hexMac):
"""
converts hex MAC string to list
:param hexMax: MAC address to convert (string)
:returns: list of MAC address integers
"""
return [int(i,16) for i in hexMac.split('-')] |
def check_prefixes(parsed, expected_prefixes):
"""Make sure each rank has the expected prefix"""
for name, prefix in zip(parsed, expected_prefixes):
try:
obs, level_name = name.split('__', 1)
except ValueError:
return False
if obs != prefix:
return Fa... |
def get_local_file_name(cur_key):
"""
Return the local file name for a given cost usage report key.
If an assemblyID is present in the key, it will prepend it to the filename.
Args:
cur_key (String): reportKey value from manifest file.
example:
With AssemblyID: /koku/20180701-2... |
def manhattan_infinity(obj1, obj2):
"""
Manhattan measure, under L_infinity standard, used in competitive learning mode.
d(x, w_i) = \max_{j} (x_j - w_{ij})
"""
return max(map(lambda obj: obj[0] - obj[1], zip(obj1, obj2))) |
def fwd_slash(file_path):
"""Ensure that all slashes are '/'
Args:
file_path (st|Path): The path to force '/'
Returns:
(str): Formatted path
"""
return str(file_path).replace("\\", "/") |
def cmp(a,b):
"""3-way comparison like the cmp operator in perl"""
if a is None:
a = ''
if b is None:
b = ''
return (a > b) - (a < b) |
def isBinAvailableInPath(name: str):
"""Check whether `name` is on PATH and marked as executable."""
from shutil import which
return which(name) is not None |
def reverse_orient(orient):
"""Reverse orientation."""
if not orient:
return orient
hours = 12.0 - float(orient.replace(',', '.'))
if hours == 12.0:
hours = 0.0
return "{0:0.1f}".format(hours).replace('.', ',') |
def infer_object_package(obj):
"""
Infer the package that defines this object.
"""
module = obj.__class__.__module__
return module.split('.')[0] |
def iou(box1, box2):
"""Compute the Intersection-Over-Union of two given boxes.
Args:
box1: array of 4 elements [cx, cy, width, height].
box2: same as above
Returns:
iou: a float number in range [0, 1]. iou of the two boxes.
"""
lr = min(box1[0]+0.5*box1[2], box2[0]+0.5*box2[2]) - \
max(box... |
def file_path_name(file_path, data_frame):
"""
Returns the file path name.
Parameters:
------
file_path: (str)
the name of the file path
data_frame: (str)
the name of the dataframe
Returns:
-------
The fill filepath name: (str)
"""
texts = file_path + data_frame +... |
def init_record(msg):
"""Initialize a TaskRecord based on a request."""
header = msg['header']
return {
'msg_id' : header['msg_id'],
'header' : header,
'content': msg['content'],
'metadata': msg['metadata'],
'buffers': msg['buffers'],
'submitted': header['date... |
def _no_tiebreak(winners, n=1):
"""
Given an iterable of possibly tied `winners`, return None if there are more
than `n` tied.
"""
if len(winners) <= n:
return winners
else:
return [None] |
def _is_builtin(obj):
"""Check if an object need not be converted."""
return isinstance(obj, (float, int, str, bool)) |
def large_straight(dice):
"""Score the given roll in the 'Large Straight' category.
"""
if sorted(dice) == [2, 3, 4, 5, 6]:
return sum(dice)
else:
return 0 |
def _parse_record(record, entry_map):
"""Parses a list of string fields into a dictionary of integers."""
if not record:
return {}
try:
return {
key: int(record[idx]) for idx, key in entry_map
}
except IndexError:
return {} |
def address_of(item):
"""
Given an attribute access, return the string address of that attribute:
test = proxy('pCube1')
address_of(test.tx)
>> 'pCube1.tx'
if <item> is a string, it's returned unchanged.returned
This function is primarily useful for mixing more elaborate f... |
def largest_odd_times(L):
""" Assumes L is a non-empty list of ints
Returns the largest element of L that occurs an odd number
of times in L. If no such element exists, returns None """
# Andrey Tymofeiuk: Sometimes double mistake leads to peculiar right result
dict_collect = {}
... |
def _deep_tuple(x):
"""Converts nested `tuple`, `list`, or `dict` to nested `tuple`."""
if hasattr(x, 'keys'):
return _deep_tuple(tuple(x.items()))
elif isinstance(x, (list, tuple)):
return tuple(map(_deep_tuple, x))
return x |
def get_param_value(name_param, list_of_results):
"""list of results is a list of lmfit ``ModelResult``."""
values = []
stderrs = []
for result in list_of_results:
values.append(result.params[name_param].value)
return values |
def undirect(edge):
"""Normalize edges so that an edge and its reverse compare equal. For
multigraph edges, assume that edge indices correspond.
"""
return (*sorted(edge[:2]), *edge[2:]) |
def fuzzy_row_key(rdata, col):
"""
Lookup correct index using closest col name.
If the col has trailing Nones, these are ignored
return -- key
"""
# Todo: Normalize rdata first
try:
# Remove trailing Nones.
col = col[:col.index(None)]
except ValueError:
# No ... |
def _filter_type_list(chromecast_list, type_name):
"""Get all chromecasts with cast_type equals to type_name"""
is_type = lambda cc: cc.device.cast_type == type_name
return tuple(filter(is_type, chromecast_list)) |
def map_ind(x):
"""Map the abbreviated names for the industries to their full name.
Parameters
----------
x : str
row in the disruption dataframe.
Returns
-------
x : str
mapped abbrevation to full name for the specific row in the disruption dataframe.
"""
ind_map ... |
def check_path(path):
"""Check if path ends with a slash ('/'). Else, it adds a slash.
The function also creates the directory if it does not existing.
Parameters
----------
path : str
A path
Returns
-------
path : str
A functional path
"""
from os import ... |
def polynomiale(a : int, b : int, c : int, d : int, x : int) -> int:
"""Retourne la valeur de a*x^3 + b*x^2 + c*x + d
"""
return (a*x*x*x + b*x*x + c*x + d) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.