content stringlengths 42 6.51k |
|---|
def compute_min_value(ad_bits):
"""Compute the min value for the codebook with codewords of length ad_bits
:param ad_bits: codeword length
:type ad_bits: int
:return: min value
:rtype: int
"""
tab = [0, None, 1, 6, 18, 83, 376, 1264, 5263, 17580, 72910]
return tab[ad_bits] |
def solution1(A):
"""
Assumes A is an unsorted list and this implementation makes no attempt at pre-sorting numbers.
:param A: List - An unsorted list of ints
:returns: int - the smallest positive integer (greater than 0) that does not occur in A
"""
if 1 not in A: return 1
smallest = 10000... |
def rotate_matrix(matrix):
"""rotates a matrix 90 degrees clockwise"""
n = len(matrix)
for layer in range(n // 2):
first, last = layer, n - layer - 1
for i in range(first, last):
# save top
top = matrix[layer][i]
# left -> top
matrix[layer][i]... |
def get_codelist_values(elements: list) -> list:
"""
Returns list of code list values as strings for all elements (except the ones with no value)
The value can be in the element attribute or text node.
:param elements : The elements to check
"""
values = []
for element in elements:
... |
def elite_selection(population, elite_num):
"""
Uses elite selection to pick elite_num units from population
:param population: population to be picked from
:param elite_num: number of units to be selected
:return: array of selected units
"""
return population[:elite_num] |
def keep_file(filepath):
"""Decide if we keep the filepath, solely by exlcusion of end of path
This is primarily to avoid keeping .pyc files
>>> keep_file('/foo.pyc')
False
"""
ignoredpathendings = ['.pyc',]
for ending in ignoredpathendings:
if filepath.endswith(ending):
... |
def process_results(results):
"""Construct the request response into a
slightly more intuitive structure
"""
response = {}
try:
response['count'] = int(results['d']['__count'])
except:
response['count'] = None
if 'error' in results.keys():
response['error'] = result... |
def fibonacci(num):
"""
Use fibonacci as test case for int variable names
"""
count = 0
if num < 0:
return None
elif num == 0:
return 0
elif num == 1 or num == 2:
return 1
else:
return fibonacci(num - 1) + fibonacci(num - 2) |
def tolist(data):
"""
if data is a string, convert to [data]
if already a list, return the list
input:
data : str or list of str
output:
data : list of str
"""
if isinstance(data, str):
return [data]
return data |
def force_str_2_bool(bool_str: str, raise_if_unknown: bool = False) -> bool:
"""convent 'True' or 'False' to bool, using on query_param"""
if isinstance(bool_str, bool):
return bool_str
if bool_str in ["True", "true", "1"]:
return True
elif bool_str in ["False", "false", "0"]:
r... |
def rotate_grid(grid):
"""
Rotates the input 90 degrees clockwise
:param list grid: input with nested lists to format
"""
return list(zip(*grid[::-1])) |
def is_cython_function(fn):
"""Checks if a function is compiled w/Cython."""
if hasattr(fn, "__func__"):
fn = fn.__func__ # Class method, static method
name = type(fn).__name__
return (
name == "method_descriptor"
or name == "cython_function_or_method"
or name == "builti... |
def _normalize_managed_link(managed_link) -> dict:
"""
Update Api-doc version
Args:
file_path': 'str',
version_info: 'str'
Returns:
"""
n_normalized = {}
for key, value in managed_link.items():
n_key = key.replace('_', ' ')
n_v... |
def color_brightness(color):
"""Calculate the brightness of an RGB color as a value between 0 and 1."""
r = float(color["r"])
g = float(color["g"])
b = float(color["b"])
if "cs" in color and color["cs"].lower() != "srgb":
# Generic fallback. https://www.w3.org/TR/AERT/#color-contrast
... |
def midpoint(pt1, pt2):
"""Computes the midpoint between two points"""
x = pt2[0]+int((pt1[0]-pt2[0])/2)
y = pt2[1]+int((pt1[1]-pt2[1])/2)
return (x,y) |
def filter_results(analysis_results, name):
"""Filter list of analysis results by result name"""
for result in analysis_results:
if result.name == name:
return result
return None |
def retry_http(response):
"""Retry on specific HTTP errors:
* 429: Rate limited to 50 reqs/minute.
Args:
response (dict): Dynatrace API response.
Returns:
bool: True to retry, False otherwise.
"""
retry_codes = [429]
code = int(response.get('error', {}).get('code', 200))
... |
def filter_below(threshold, results):
"""Filters items below a certain threshold out."""
out_list = []
for line in results:
if line['validation_acc'] > threshold:
out_list.append(line)
return out_list |
def get_version_from_tag(tag):
"""Handles 1.5.0 or v1.5.0"""
return tag[1:] if tag.startswith('v') else tag |
def int_or_tuple(value):
"""Converts `value` (int or tuple) to height, width.
This functions normalizes the input value by always returning a tuple.
Args:
value: A list of 2 ints, 4 ints, a single int or a tf.TensorShape.
Returns:
A list with 4 values.
Raises:
ValueError:... |
def sanitize_dictlist(dict_list):
"""Do some cleanup. String 'True' and 'False' must be
interpreted as bool values. Empty string should evaluate
to None."""
for element in dict_list:
for key,value in element.items():
if value == 'False': element[key] = False
if value ... |
def kahan_sum(list_of_floating_point_numbers):
"""
Computes the sum of a list of floating point numbers, correcting for precision loss.
Parameters:
----------
list_of_floating_point_numbers: ndarray
Returns:
-------
Sum of the elements.
"""
suma = 0.0
c = 0.0
for i in r... |
def file_comparison(files0, files1):
"""Compares two dictionaries of files returning their difference.
{'created_files': [<files in files1 and not in files0>],
'deleted_files': [<files in files0 and not in files1>],
'modified_files': [<files in both files0 and files1 but different>]}
... |
def sort(s, reverse=False):
"""
Sort given string by ascending order.
If reverse is True, sorting given string by descending order.
"""
return ''.join(sorted(s, reverse=reverse)) |
def numeric_cast (v):
"""Try to cast values to int or to float"""
if type(v)== str:
try:
v = int(v)
except ValueError:
try:
v = float(v)
except ValueError:
pass
return v |
def save_str_as_file(str, filepath):
"""Save a string to a file and return the file path.
Keyword arguments:
str - the string that you want to save as in a file
filepath - the path to the file that you want to save the string to
"""
with open(filepath, "w", encoding="utf-8") as file:
... |
def clean_nginx_git_tag(tag):
"""
Return a cleaned ``version`` string from an nginx git tag.
Nginx tags git release as in `release-1.2.3`
This removes the the `release-` prefix.
For example:
>>> clean_nginx_git_tag("release-1.2.3") == "1.2.3"
True
>>> clean_nginx_git_tag("1.2.3") == "1... |
def bytes_to_readable(bytes_value):
"""
Convert bytes to a readable form
:param bytes_value: int, bytes
:return: string, readable value, like 1GB
"""
from math import ceil
if bytes_value > 1073741824:
# 1073741824 = 1024 * 1024 * 1024
# bytes to gigabytes
readable_val... |
def is_tracked_zone(cname, zones):
"""
Is the root domain for the provided cname one of the known domains?
"""
for zone in zones:
if cname.endswith("." + zone) or cname == zone:
return True
return False |
def part_exists(partitions, attribute, number):
"""
Looks if a partition that has a specific value for a specific attribute
actually exists.
"""
return any(
part[attribute] and
part[attribute] == number for part in partitions
) |
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
level -= 1
try:
if package.count('.') < level:
raise ValueError("attempted relative import beyond top-level "
"package")
except AttributeError:
... |
def str_to_date(_data: str) -> str:
"""
formata a string da data para um formato que possa ser inserido no banco como date
:param _data: str
:return: str
"""
return str(_data)[-4:] + '-' + str(_data)[-6:-4] + '-' + str(_data)[:-6] |
def set_async_call_stack_depth(maxDepth: int) -> dict:
"""Enables or disables async call stacks tracking.
Parameters
----------
maxDepth: int
Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async
call stacks (default).
"""
return {
... |
def db2mag(x):
""" Converts from dB to magnitute ratio
Parameters
----------
x - Input in dB
Returns
-------
m - magnitude ratio
"""
m = 10.0 ** (x / 20.0)
return m |
def sign(number):
"""Returns 1 if number is positive, -1 if number is negative and 0 if number is 0"""
if number < 0:
return -1
elif number > 0:
return 1
else:
return 0 |
def _convert(text, mapping):
""" Convert the text using the mapping given """
for key, value in mapping.items():
if isinstance(value, str):
text = text.replace(key, value)
else:
while key in text:
for actualValue in value:
text ... |
def pluralize(apitools_collection_guess):
"""Pluralize krm_kind and handle common atypical pluralization cases."""
ending_plurals = [('Policy', 'Policies'), ('Proxy', 'Proxies'),
('Repository', 'Repositories'), ('Index', 'Indexes'),
('Address', 'Addresses')]
found_plural = ... |
def parse_hashtag_string(hashtags: str) -> list:
"""Parses string of hashtags returns list."""
return list(set([item.strip() for item in hashtags.split("#") if item != ""])) |
def vec_2_str(vec):
"""
Convert vector of integers to string.
:param vec: [int, int, ...]
:return: string
"""
char_vec = [chr(i) for i in vec]
return ''.join(char_vec) |
def get_scenario_start_index(base_times, scenario_start_time):
"""
Returns the index of the closest time step that is at, or before the scenario start time.
"""
indices_after_start_index = [
idx for idx, time in enumerate(base_times) if time > scenario_start_time
]
if not indices_after_s... |
def ujoin(*args):
"""Join strings with the url seperator (/).
Note that will add a / where it's missing (as in between 'https://pypi.org' and 'project/'),
and only use one if two consecutive tokens use respectively end and start with a /
(as in 'project/' and '/pipoke/').
>>> ujoin('https://pypi.o... |
def foo2(value):
"""Bare return statement implies `return None`"""
if value:
return value
else:
return |
def is_float(string):
"""
Check whether string is float.
See also
--------
http://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python
"""
try:
float(string)
return True
except ValueError:
return False |
def get_objects_name(train_files):
"""
returns: object name, unique str in case of shapenet
given names in case of pallet
"""
objs = list()
for t in train_files:
splits = t.split('/')[-1]
obj = splits[:-4]
objs.append(obj)
return objs |
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: ?
Space Complexity: ?
"""
if nums == None or len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
max_... |
def js_lang_fallback(lang_name, js_name=None):
"""
Return the fallback lang name for js files.
:param a :class:`str:`
:param js_name: a :class:`str:`, optional.
:return: a :class:`str:`
"""
# The mapping is crap, we use a special case table to fix it.
if js_name == "fullcalendar":
... |
def mag_zeropoint(filter_name):
"""
Given a filter name, return the number of photons per square centimeter per second
which a star of zero'th magnitude would produce above the atmosphere. We assume that the star
has a spectrum like Vega's.
The numbers are pre-calculated and we just pick the approp... |
def make_virtual_offset(block_start_offset, within_block_offset):
"""Compute a BGZF virtual offset from block start and within block offsets.
The BAM indexing scheme records read positions using a 64 bit
'virtual offset', comprising in C terms:
block_start_offset << 16 | within_block_offset
Here ... |
def data_consistency(k, k0, mask, noise_lvl=None):
"""
k - input in k-space
k0 - initially sampled elements in k-space
mask - corresponding nonzero location
"""
v = noise_lvl
if v: # noisy case
out = (1 - mask) * k + mask * (k + v * k0) / (1 + v)
else: # noiseless case
... |
def groupby_type(estimators):
"""
finds the number of estimators for each estimator class
:param estimators: list of estimators (not necessarily trained)
:return: a dictionary of estimator class as key and frequency as value
"""
unique_classes = {}
for estimator in estimators:
clf_na... |
def split(string, separator=None, max_splits=-1):
""":yaql:split
Returns a list of tokens in the string, using separator as the
delimiter.
:signature: string.split(separator => null, maxSplits => -1)
:receiverArg string: value to be splitted
:argType string: string
:arg separator: delimite... |
def _get_exclude_files(old_baseline):
"""
Older versions of detect-secrets always had an `exclude_regex` key,
this was replaced by the `files` key under an `exclude` key in v0.12.0
:rtype: str|None
"""
if old_baseline.get('exclude'):
return old_baseline['exclude']['files']
if old_ba... |
def PssmValidator(pssm):
"""validate each PSSM matrix format, no head.
pssm = [[], [], ... , []]
"""
for pos in pssm:
if len(pos) != 4:
return False
for base in pos:
try:
float(base)
except ValueError:
return False
r... |
def linesegmentsintersect(p1, p2, q1, q2):
"""Checks if two line segments intersect.
Input:
p1 : The start vertex of the first line segment.
p2 : The end vertex of the first line segment.
q1 : The start vertex of the second line segment.
q2 : The end vertex of the second line se... |
def has_str_prefix(value: str) -> bool:
"""
Inspect a token value of type string to check if it has a
prefix or contains escaped characters.
Args:
value (str): the string value of this token
Returns:
Boolean defining whether value has a prefix
"""
string_prefix = ["r", "u",... |
def flatten_verifications(old_verifications):
""" Convert verifications from v1 to v2 """
new_verifications = []
for key in old_verifications:
verification = old_verifications[key]
verification['key'] = key
new_verifications.append(verification)
return new_verifications |
def get_iptc_seg(segments):
"""Returns iptc from JPEG meta data list
"""
for seg in segments:
if seg[0:2] == b"\xff\xed":
return seg
return None |
def get_processing_instructions(body):
""" Extract the processing instructions / acl / etc. at the beginning of a page's body.
Hint: if you have a Page object p, you already have the result of this function in
p.meta and (even better) parsed/processed stuff in p.pi.
Returns a list of... |
def is_char_field(model_field):
"""
Checks if a model field is a char field.
"""
class_name = model_field.__class__.__name__
return class_name == 'CharField' |
def _list_d2s(int_list):
"""Converts a list of ints to strings."""
return ["{:d}".format(x) for x in int_list] |
def cssid(input):
"""Custom filter"""
return f"#{input}" |
def cast_uint(value):
"""
Cast value to 32bit integer
Usage:
cast_int(1 << 31) == 2147483648
"""
value = value & 0xFFFFFFFF
return value |
def make_great(magicians):
"""Modify each magician name in a list."""
great_magicians = []
while magicians:
great_magicians.append(magicians.pop() + " the Great")
return great_magicians |
def head_of_all(x, l):
"""List of lists from l where x is the head of all the lists."""
return [[x] + p for p in l] |
def _check_sorting_runs(candidates, id_char):
"""helper to ensure correct run-parsing and mapping"""
run_idx = [f.find(id_char) for f in candidates]
for config, idx in zip(candidates, run_idx):
assert config[idx - 1].isdigit()
assert not config[idx - 2].isdigit()
runs = [int(f[idx - 1]) ... |
def read_float(field: str) -> float:
"""Read a float."""
return float(field) if field != "" else float('nan') |
def isValidArgument(s):
"""Returns whether s is strictly a valid argument for an IRC message."""
return '\r' not in s and '\n' not in s and '\x00' not in s |
def _IsReadableStream(obj):
"""Checks whether obj is a file-like readable stream.
:rtype:
boolean
"""
if (hasattr(obj, 'read') and callable(getattr(obj, 'read'))):
return True
return False |
def format_team(team_id, name, div_id):
"""
Helper for team row formatting
"""
data_point = {}
data_point["ID"] = team_id
data_point["Name"] = name
data_point["DivisionID"] = div_id
return data_point |
def calc_delta(r, aa):
"""
Calculate ubiquitous function on Kerr spacetimes.
Parameters:
r (float): radius
aa (float): spin parameter (0, 1)
Returns:
delta (float)
"""
# return r * r - 2 * r + aa * aa
return r * (r - 2) + aa * aa |
def priority_offset(priority):
"""
Args:
priority:
Returns:
"""
if priority == 'low':
return .7
elif priority == 'medium':
return .5
elif priority == 'high':
return .3
else:
return .1 |
def tree_binary(t):
"""Returns true just in case `t` is locally binary branching."""
return (len(t) == 2) |
def generate_splits_name(y_size, z_size, x_size, Y_size, Z_size, X_size,
out_dir, filename_prefix, extension):
"""
generate all the splits' name based on the number of splits the user set
"""
split_names = []
for x in range(0, int(X_size), int(x_size)):
for z in rang... |
def epsilon(dtype):
"""A simple way to determine (at runtime) the precision of a given type
real number.
Precision is defined such that (1.0 + epsilon(dtype) > 1.0).
Below this number, the addition will not yield a different result.
"""
one = dtype(1.0)
small = one
small2 = small
while one + small > o... |
def list_check(lst):
"""Are all items in lst a list?
>>> list_check([[1], [2, 3]])
True
>>> list_check([[1], "nope"])
False
"""
t = [1 if isinstance(x, list) else 0 for x in lst]
return len(lst) == sum(t) |
def _clean_string(value):
"""
Return `str(value)` if it's a string or int, otherwise "".
"""
if isinstance(value, (int,) + (str,)):
return str(value)
return "" |
def canConstruct_v2(ransomNote: str, magazine: str) -> bool:
"""The LeetCode solution runner judges this as the fastest solution of all four."""
for letter in set(ransomNote):
if ransomNote.count(letter) > magazine.count(letter):
return False
return True |
def add_protocol(x):
"""Add https protocol to link"""
return f"https:{x}" if x.startswith("//") else x |
def get_cancer_types(file_paths_by_cancer):
"""
Maps cancer type to an index value
Parameters:
file_paths_by_cancer: (dict) cancer : list of data files
Returns:
cancer_dict: (dict) cancer : integer identifier
"""
cancer_dict = {}
cancer_index = 0
for cancer in file_paths_by_c... |
def dt_calc(etime):
"""Returns an interval of time that increased as the ellapsed time etime increases"""
if etime <= 60:
return 5
elif etime <= 300:
return 10
elif etime <= 600:
return 30
elif etime <= 3600:
return 60
else:
return 300 |
def pyopenssl_callback(conn, cert, errno, depth, ok):
"""Callback method for _get_cert_alternate"""
if depth == 0 and (errno == 9 or errno == 10):
return False
return True |
def to_tuple(lst):
"""Recursively convert nested lists to nested tuples."""
return tuple(to_tuple(i) if isinstance(i, list) else i for i in lst) |
def UFP_(kexo,Sexo,kendo,kin,kout,Aspine):
"""Returns the fixed point of the mobile receptor pool.
Parameters
----------
kexo : float
Rate of exocytosis events occuring at the spine.
Sexo : float
Exocytosis event size.
kendo : float
Rate at which receptors are endocytose... |
def resolve_conflicts(inputs, outputs):
"""
Checks for duplicate inputs and if there are any,
remove one and set the output to the max of the two outputs
Args:
inputs (list<list<float>>): Array of input vectors
outputs (list<list<float>>): Array of output vectors
Returns:
tup... |
def abs_value_equal(x, y):
"""Return whether or not the absolute value of both numbers is the same.
Please refrain from using libraries (abs)
>>> abs_value_equal(-2, -2)
True
>>> abs_value_equal(-3, 3)
True
>>> abs_value_equal(1, 2)
False
>>> abs_value_equal(3, 3)
True
>>> ... |
def norm_label(y, left_min, left_max, right_min, right_max):
"""
normalise the value
:param y: original value
:param left_min: original min
:param left_max: original max
:param right_min: desired min
:param right_max: desired max
:return:
normalised steering angle
"""
left_sp... |
def json_patch(from_obj, to_obj, ignore_keys=None, only_keys=None, no_remove=False):
"""
Creates a JSON patch diff between two objects.
Arguments:
from_obj (dict): from object, usually the existing object returned by API
to_obj (dict): to object, usually the new object to return
Keyword argume... |
def full_dict(ldict, keys):
"""Return Comparison Dictionaries
from list dict on keys
keys: a list of keys that when
combined make the row in the list unique
"""
if type(keys) == str:
keys = [keys]
else:
keys = keys
cmp_dict = {}
for line in ldict:
in... |
def quick_sort_out_of_place(array):
"""Recursive QuickSort Implementation:
- O(nlog(n)) time
- O(n) space (out of place)
- unstable
- pivot = mean of the range (best on normal, numerical distributions)
"""
# Base Case
if len(array) < 2:
return array
# Recurisive Case - choose... |
def prefixed_with_varlong(buf, mlen=10):
"""
Returns whether the data is prefixed with what is probably a valid varint
"""
for i in range(mlen):
if len(buf) <= i:
return False
if buf[i] & 0x80 == 0x00:
return True
return False |
def remove_quotes(value, unused):
"""Remove quotes helper."""
return value.replace('"', "") |
def interpolateLinear(
y1, #
y2, #
x # weighting [0..1]. 0 would be 100 % y1, 1 would be 100 % y2
):
"""
simple linear interpolation between two variables
@param y1
@param y2
@param x weighting [0..1]: 0 would be 100 % y1, 1 would be 100 % y2
@return the interpolated value
"""
return y1 * (1.0 - x) + y... |
def remove_spaces(input_text, main_rnd_generator=None, settings=None):
"""Removes spaces.
main_rnd_generator argument is listed only for compatibility purposes.
>>> remove_spaces("I love carrots")
'Ilovecarrots'
"""
return input_text.replace(" ", "") |
def guess_keys(data):
"""Guess keys should be uniform from first item
"""
return list(data[0].keys()) |
def lr_schedule(epoch):
"""Learning Rate Schedule
Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs.
Called automatically every epoch as part of callbacks during training.
# Arguments
epoch (int): The number of epochs
# Returns
lr (float32): learning rate
""... |
def drop_role(role):
"""Helper method to construct SQL: drop role."""
return f"DROP ROLE IF EXISTS {role};" |
def get_positions(start_idx, end_idx, length):
""" Get subj/obj position sequence. """
return list(range(-start_idx, 0)) + [0] * (end_idx - start_idx + 1) + \
list(range(1, length - end_idx)) |
def _get_random_seeds(i):
"""
returns 10 seeds
"""
seed_list = [42, 103, 13, 31, 17, 23, 46, 57, 83, 93]
return seed_list[i - 1] |
def splitFullFileName(fileName):
"""
split a full file name into path, fileName and suffix
@param fileName
@return a list containing the path (with a trailing slash added), the
file name (without the suffix) and the file suffix (without the
preceding dot)
"""
tmp = fileName.split... |
def score_by_source_ips(event, attributes):
""" Score based on number of source IPs implicated """
score = 0
for attribute in attributes:
if attribute["category"] == "Network activity":
ty = attribute["type"]
if ty == "ip-src":
score += 3
return score |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.