content stringlengths 42 6.51k |
|---|
def find_real_ancestors(curr_weights, predecessors, real_nodes):
"""
A recursive function that replaces a layer's parents in the graph with real layers,
instead of intermediate tensor names.
Args:
curr_weights: current weights left to be processed
predecessors: the graph connections
... |
def exclude_pattern(f):
"""
Return whether f is in the exclude pattern.
Exclude the files that starts with . or ends with ~.
"""
return f.startswith(".") or f.endswith("~") |
def meanValue(inputArray):
"""
meanValue
Function used to calculate the mean value of an array
@param inputArray Array passed for calculation
@return meanValueReturn The integer value returned by the calculation
"""
meanValueReturn = sum(inputArray)/float(len(inputArray))
return meanValu... |
def convert_tensor_to_numpy(tensor):
"""
Convert from various forms of pytorch tensors
to numpy arrays.
Note: torch tensors can have both "detach" and "numpy"
methods, but numpy() alone will fail if tensor.requires_grad
is True.
"""
if hasattr(tensor, "detach"): # pytorch tensor with a... |
def is_valid_group(group_name, nova_creds):
"""
Checks to see if the configuration file contains a SUPERNOVA_GROUP
configuration option.
"""
valid_groups = [value['SUPERNOVA_GROUP'] for key, value in
nova_creds.items() if 'SUPERNOVA_GROUP'
in nova_creds[key].k... |
def _customIndex(l, element, N=0):
"""
Custom Index function so that you can find the Nth occurence of an element
"""
parts = l.split(element, N+1)
if len(parts) <= N+1:
return -1
return len(l)-len(parts[-1])-len(element) |
def oldest_ancestor(candidate):
"""
finds the top parent of the candidate
"""
try:
parent = candidate.parent
except AttributeError:
return candidate
else:
return oldest_ancestor(parent) |
def longest_palindrome_subseq(sequence: str) -> int:
"""
Some examples
>>> longest_palindrome_subseq('sdsda')
3
>>> longest_palindrome_subseq('cbbd')
2
>>> longest_palindrome_subseq('as')
1
>>> longest_palindrome_subseq('l')
1
>>> longest_palindrome_subseq('')
0
"""
... |
def str2val(val, format="%5.2f", na="na", list_detection=False):
"""guess type (int, float) of value.
If `val` is neither int nor float, the value
itself is returned.
"""
if val is None:
return val
def _convert(v):
try:
x = int(v)
except ValueError:
... |
def screen_errors(error_message, *args, **kwargs):
"""
Make sure that the values passed as args and the keys in kwargs do not appear in error messages
parameter: (string) error_message
The error message that needs to be screened for the values in args and the keys
in kwargs
parameter: ... |
def getIntersections(intervals):
"""return regions were two intervals are overlapping.
"""
if not intervals:
return []
intervals.sort()
max_to = intervals[0][1]
all_sections = []
sections = [intervals[0][0], intervals[0][1]]
for this_from, this_to in intervals[1:]:
# ... |
def edit_distance(a: str, b: str) -> int:
"""Compute the edit distance between strings a and b.
Uses the optimal string alignment algorithm according to:
https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
>>> edit_distance("abcd", "abcd")
0
>>> edit_distance("abcd", "bcd")
... |
def load_conf_option_to_dict(key_value_option):
"""Convert the uplinkset and flat_net mappings value to a dict.
It converts the value from the Config fields uplinkset_mappings
and or flat_net_mappings to a dict object. The object returned
is in the format:
{
provider_from_uplinkset_mapping:... |
def find_k_factor(length, k_factor):
"""Find the number of strings of length `length` with K factor = `k_factor`.
Keyword arguments:
length -- integer
k_factor -- integer
"""
mat=[[[0 for i in range(4)]for j in range((length-1)//3+2)]for k in range(length+1)]
if 3*k_factor+1>length:
... |
def label_from_id(id_string):
"""
Returns a label string constructed from the suppliued Id string
Underscore characters in the Id are replaced by spaces.
The first character may be capirtalized.
>>> label_from_id("entity_id") == "Entity id"
True
"""
temp = id_string.replace('_', ' ').... |
def get_severity(data):
"""Convert level value to severity
"""
if 'warning' == data:
return 'Medium'
elif 'error' == data:
return 'Critical'
else:
return 'Info' |
def _map_header_2_multilevel(map_header):
""" Convert dictionary with mapping of columns to multiindex. """
map_header2 = {}
for key, value in map_header.items():
map_header2[(key, '')] = (value, '')
return map_header2 |
def user_model(username, **kwargs):
"""Return a user model"""
user = {
'username': username,
'scope': 'basic',
}
user.update(kwargs)
return user |
def check_sim(l):
"""check the sim list"""
log = ' --- OK ---'
for x,y in l:
i=0;j=0
for a,b in l:
if a==x: i+=1
if b==y: j+=1
if (i>1 or j>1):
log = " --- !ERROR! --- "
break
return log |
def params_2(kernels, time_2, output_time_format, output_time_custom_format):
"""Input parameters from WGC API example 2."""
return {
'kernels': kernels,
'times': time_2,
'output_time_format': output_time_format,
'output_time_custom_format': output_time_custom_format,
} |
def has_digits(s):
"""
This function checks whether a string
contains any digits
Arguments
s : string
Returns
(bool) True / False
"""
return len([char for char in s if char.isdigit()]) != 0 |
def nice_size(size):
"""
Returns a readably formatted string with the size
>>> nice_size(100)
'100 bytes'
>>> nice_size(10000)
'9.8 KB'
>>> nice_size(1000000)
'976.6 KB'
>>> nice_size(100000000)
'95.4 MB'
"""
words = ['bytes', 'KB', 'MB', 'GB', 'TB']
try:
siz... |
def is_within_interval(value, min_value=None, max_value=None):
"""
Check whether a variable is within a given interval. Assumes the value is
always ok with respect to a `None` bound. If the `value` is `None`, it is
always within the bounds.
:param value: The value to check. Can be ``None``.
:pa... |
def sort_dict(d, reverse=False):
"""
Return sorted dict; optionally reverse sort.
"""
return dict(sorted(d.items(), key=lambda x: x[1], reverse=reverse)) |
def parse_version(version):
"""Parse version string in a tuple, if version is an invalid string
returns None"""
# version = <str>
# vs = <str>
# return <NoneType>|(*<int>)
version = str(version).split('.')
if len(version) != 3:
return None
if all(vs.isdigit() for vs in version):
... |
def data_formatter(value, val_type, field=None):
"""Return formatted data."""
# If val_type is int/num, but the value is not
# this function will just return the string
# schema validation will report the error
try:
if val_type in ["int", "integer"]:
return int(value)
eli... |
def scale_float_value(val, ll, ul):
"""Scale a value based on the lower/upper limits"""
return (val - ll) / (ul - ll) |
def dms_to_dd(degrees, minutes, seconds):
"""Convert degrees, minutes, seconds to decimal degress"""
fd = float(degrees)
if fd < 0:
return fd - float(minutes) / 60 - float(seconds) / 3600
return fd + float(minutes) / 60 + float(seconds) / 3600 |
def intersection(L1, L2, debug = False):
"""Intersects two line segments
Args:
L1 ([float, float]): x and y coordinates
L2 ([float, float]): x and y coordinates
Returns:
bool: if they intersect
(float, float): x and y of intersection, if they do
"""
D = L1[0] * L2[1]... |
def evaluates_uniquely(objects, func) -> bool:
"""Return true if the return value of ``func`` is unique among
``objects``.
This can be used to check whether some attribute `obj.attr` is
unique among a set of such objects, and can thus be used as a key.
**Usage:**
>>> from operator import item... |
def good_l_flag(flag):
"""
returns True if flag is a '-l' flag we need to handle
"""
return flag.startswith('-l') and not flag.startswith('-lpython') and not flag == '-ldl' |
def unique_hashtag(dic):
"""dict of {str: list of str} -> dict of {str: list of str}}
Return a dictionary with hashtag as keys and candidate in dic as values.
>>> dic = {'D': ['a', '1', '2'], 'M': ['a', 'i'], 'N': ['1', '0', '']}
>>> unique_hashtag(dic) == {'2': 'D', 'i': 'M', '0': 'N', '': 'N... |
def package_collection(distinct: bool):
"""Return the package collection, set or list."""
if distinct:
package = set()
else:
package = []
return package |
def get_positions_from_delta_positions(delta_steps):
"""
:param delta_steps: array of delta positions of 2 joints for each of the 4 feet
:return: array of positions of 2 joints for each of the 4 feet
"""
steps = []
for i, step in enumerate(delta_steps):
if i == 0:
steps.appe... |
def find_documented_methods(clas):
"""
Find all the public methods of a given class that have a nonempty documentation, filtering the methods documented
the exact same way in a superclass.
"""
public_attrs = {a: getattr(clas, a) for a in dir(clas) if not a.startswith("_")}
public_methods = {a: m... |
def compile_output_errors(
is_filename_error,
filename_error_output,
is_error,
forecast_error_output
):
"""
purpose: update locally_validated_files.csv and remove deleted files
params:
* filepath: Full filepath of the forecast
* is_filename_error: Filename != file path (True/False)
... |
def evalSumLists(lists=[[.25, .75, .1], [-1, 0], [4, 4, 4, 4]]):
"""
task 0.5.12
sum lists of lists
"""
return sum([sum(x) for x in lists]) |
def roman_to_int(roman):
"""convert roman numeral to integer"""
num_map = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
"IV": -2,
"IX": -2,
"XL": -20,
"XC": -20,
"CD": -200,
"CM": -200,
... |
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
"*** YOUR CODE HERE ***"
while n>0:
... |
def get_bag_contents(bag, bag_rules):
"""Get all bags that are inside a bag"""
content = []
for n, item in bag_rules[bag].items():
content += [n] * item
return content |
def create_figure_div(title, details, fig1_file, fig2_file=None):
"""
Create html code to generate scan details div
:param title: str title (single line)
:param details: str details of scan (multi-line)
:param fig1_file: str
:param fig2_file: str or None
:param class_name: str
:return:
... |
def is_url(string):
"""
Checks if the given string starts with 'http(s)'.
"""
try:
return string.startswith("http://") or string.startswith("https://")
except AttributeError:
return False |
def chars(data: bytes, pos, length)-> str:
"""null padded string"""
return data[pos:pos + length].strip(b'\0').decode('utf-8') |
def clean(value, truncate_symbols=True):
"""
:param value: basestring
:param truncate_symbols: whether to truncate symbols from string
:return: lowercase cleaned string based, alpha numeric characters if truncate_symbols=True
"""
if value:
parts = [v.lower() for v in list(value.strip())... |
def items(n):
"""A list of strings."""
return ["item{0:d}".format(i) for i in range(n)] |
def inventory_report(products):
"""Print a summary of the list of products
"""
product_count = len(products)
if product_count <= 0:
return "No products!"
total_price, total_weight, total_flam = 0, 0, 0
for prod in products:
total_price += prod.price
total_weight += pr... |
def smart_truncate(text: str, max_length: int = 100, suffix: str = '...') -> str:
"""
Returns a string of at most `max_length` characters, cutting
only at word-boundaries. If the string was truncated, `suffix`
will be appended.
In comparison to djangos defaultfilter `truncatechars` this method does ... |
def num_matches(matches):
""" Used for debugging. Count matches before/after outlier removal """
n_matches = 0
for i in range(len(matches)):
for j in range(len(matches[i])):
if j <= i: continue
n_matches += len(matches[i][j])
return n_matches |
def gaussian_lp(x: float, mean: float, var: float) -> float:
"""Analytically evaluate Gaussian log probability."""
lp = -1 / (2 * var) * (x - mean) ** 2
return lp |
def colorGrad(value, colorMin, colorMax, minValue, maxValue):
"""
returns a middle rgb color value based on the distance between max and min
"""
c_range = abs(maxValue - minValue)
v = value - min(maxValue,minValue)
v_pct = v/c_range
#v_pct *= v_pct
#print value, v_pct, colorMin, ... |
def _linterp(x, X, Y, i):
"""
The "kernel" of linear interpolation.
Parameters
----------
x : float
The evaluation site
X : ndarray(float, 1d)
The independent data.
Y : ndarray(float, 1d)
The dependent data.
i : int
The interval of `X` that contains `x... |
def iterable(y) -> bool:
"""Check whether or not an object can be iterated over.
Vendored from numpy under the terms of the BSD 3-Clause License. (Copyright
(c) 2005-2019, NumPy Developers.)
Parameters
----------
value :
Input object.
type :
object
y :
"""
try:... |
def humidity_or_none(h):
"""Return the supplied humidity percentage as a string in the
format "%2d", or a hyphen, if unavailable (None).
"""
if h is None:
return " -"
return "%2d" % h |
def ToPascalCase(s):
"""Returns APascalCase string"""
parts = s.split('_')
# Handle corner case where the original string starts or ends with an underscore
if not parts[0]:
parts[0] = '_'
if len(parts) > 1 and not parts[-1]:
parts[-1] = '_'
return ''.join([ "{}{}".f... |
def generate_pairing(count, step_hide=None):
""" generate registration pairs with an option of hidden landmarks
:param int count: total number of samples
:param int|None step_hide: hide every N sample
:return list((int, int)), list(bool): registration pairs
>>> generate_pairing(4, None) # doctest... |
def maybe_num(x):
"""Converts string x to an int if possible, otherwise a float if possible,
otherwise returns it unchanged."""
x = x.strip('[').strip(']')
try: return int(x)
except ValueError:
try: return float(x)
except ValueError: return x |
def linearFun(x1, y1, x2, y2):
"""tworzy wspolczynniki a, b funkcji liniowej y1 = ax1 + b, y2 = ax2 + b"""
a = (y2 - y1) * 1.0 / (x2 - x1)
b = y1 - a * x1
return a, b |
def DecodeFltZero(x) -> int:
"""Returns the integer representation of 32 bit float zero"""
assert x == 0
return 0 |
def make_list(arg):
"""
todo: Update Documentation
:param arg:
:type arg:
:return:
:rtype:
"""
if arg is None:
return []
if isinstance(arg, list):
return arg
return [arg] |
def _getstatusname(drev):
"""get normalized status name from a Differential Revision"""
return drev[b'statusName'].replace(b' ', b'').lower() |
def norm_Linf(a):
"""L-infinity norm"""
return max(abs(ai) for ai in a) |
def fill_missing(data):
"""
Replace 99999 and 88888 entries with nan.
"""
return [x if x not in [99999, 88888] else float('nan') for x in data] |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible \
looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the ... |
def get_result_mesg(results):
"""
Get messages for model evaluation results.
Args:
results (dict): Evaluation results with None of float values.
Return:
mesgs (dict): Messages for the corresponding results.
"""
mesgs = {}
for key, val in results.items():
... |
def check_ports(ports):
"""
Check ports to determine running gobuster and/or smbmap.
0 = none
1 = gobuster
2 = smbmap
3 = both
"""
web = 0
smb = 0
# Determine if we ports open
if (('80' in ports) or ('443' in ports)):
web = 1
# Determine if SMB ports open
if... |
def avg(lis, exception=0.0):
"""Calculates the average of a list.
lis is the list that is averaged.
exception is returned if there is a divide by zero error. The
default is 0.0 because the main usage in in percentage calculations.
"""
lis = [item for item in lis if item is not None]
if len(... |
def ed_append(filename, string):
"""
appends string to the end of the file. If the file does not exist, a new
file is created with the given file name. The function returns the number of characters written to the
file.
:param filename: file to be manipulated
:param string: string to be appended
... |
def _oid_valid_format(oid):
"""Determine whether the format of the oid is correct.
Args:
oid: OID string
Returns:
True if valid
"""
# oid cannot be numeric
if isinstance(oid, str) is False:
return False
# Make sure the oid is not blank
stripped_oid = oid.strip... |
def get_exact_match(references, candidates):
"""
Exact Matc between two smiles
"""
exact_match = 0
for img in references:
candidate_smi = ''
if img in candidates and references[img] == candidates[img]:
exact_match += 1
return exact_match |
def is_newick(filename, **kwargs):
"""
Determine if the file is of newick type
"""
return filename.endswith('.nwk') |
def parse_encoding_header(header):
""" Break up the `HTTP_ACCEPT_ENCODING` header into a dict of
the form, {'encoding-name':qvalue}.
"""
encodings = {'identity':1.0}
for encoding in header.split(","):
if(encoding.find(";") > -1):
encoding, qvalue = encoding.split(";")
... |
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
"""Python 2 doesn't have math.isclose()
Here is an equivalent function
Use this to tell whether two float numbers are close enough
considering using == to compare floats is dangerous!
2.0*3.3 != 3.0*2.2 in python!
Args:
a (float) : the firs... |
def _is_idempotence_error(status_code, errors, context):
"""
Determines if an idempotence error has occurred based on the status code, errors and context
"""
return status_code == 409 \
and context is not None \
and context.idempotence_key is not None \
and len(errors) == 1 \
... |
def address_to_integer(address):
"""Attempt to convert an address from a string (hex) to an integer."""
try:
return int(address, 16)
except:
return 0 |
def swap32(x):
"""swap endian 32 bits"""
return ((x & 0xff000000) >> 24) | \
((x & 0x00ff0000) >> 8) | \
((x & 0x0000ff00) << 8) | \
((x & 0x000000ff) << 24) |
def calculate(lst):
""" To Find Total And Average """
n = len(lst)
sum = 0
for i in lst:
sum+=i
avg = sum/n
return sum, avg |
def first(iterable, default=None):
"""Return the first element of an iterable; or default."""
return next(iter(iterable), default) |
def right_align_strings(string_list):
"""Invert the sequence of a nested list."""
right_aligned_string_list = []
for l in string_list:
right_aligned_string_list.append(l[::-1])
return right_aligned_string_list |
def clean_for_hashtag(text):
"""
Strip non alphanumeric charachters.
Sometimes, text bits are made up of two parts, sepated by a slash. Split
those into two tags. Otherwise, join the parts separated by a space.
"""
tags = []
bits = text.split('/')
for bit in bits:
# keep the alp... |
def parse_sentence_indices(cls, sep):
""" Makes valid (non-overlapping, increasing) pairs of CLS and SEP tokens. """
cls_clean, sep_clean = [], []
i = 0
while len(sep) > 0 and len(cls) > 0 and i < max(sep):
cls_idx = cls.pop(0)
while i > cls_idx:
if len(cls) == 0:
... |
def get_tester(job):
"""Returns job's tester type."""
if 'pep8' in job:
return 'pep8'
if 'unit' in job:
return 'unit'
if 'functional' in job:
return 'functional'
if 'tempest' in job:
return 'tempest'
if 'rally' in job:
return 'rally'
if 'sts' in job:
... |
def previous(some_list, current_index):
"""
Returns the previous element of the list using the current
index if it exists. Otherwise returns an empty string.
"""
try:
return some_list[int(current_index) - 1] # access the previous element
except Exception:
return '' |
def pascal(n):
"""Prints out n rows of Pascal's triangle.
It returns False for failure and True for success."""
row = [1]
k = [0]
for x in range(max(n,0)):
print(row)
row=[l+r for l,r in zip(row+k,k+row)]
return n>=1 |
def parse_turn(turn):
"""Parse the input from the user for valid player strings and play positions
Args:
turn (string): Input string from the user that contains the played
position (0-8)
Returns:
(int/None): Returns interger on success or None on failure
"""
t... |
def char_to_str_xform(line):
"""This transforms the 'char', i.e, 'char *' to 'str', Python string."""
line = line.replace(' char', ' str')
line = line.replace('char ', 'str ')
# Special case handling of 'char **argv' and 'char **envp'.
line = line.replace('str argv', 'list argv')
line = line.rep... |
def form_shell_ratio(radius, thickness, length):
"""form:shell ratio"""
return (radius+thickness)**2/((radius+thickness)**2 - radius**2) |
def isint(value):
""" To check if any variable can be converted to integer """
try:
int(value)
return True
except ValueError:
return False |
def factor_out_twos(n):
"""
Returns the tuple (d,s) such that n = d*(2**s) for the smallest value of d
"""
d = n
s = 0
while d % 2 == 0:
s += 1
d //= 2
return d,s |
def test_trimmed_average_intensity(intensities, intensity):
"""Parse line and get intensities. Find average intensity of channels,
excluding the top and bottom values. It does not skip any low values.
Return True if average above "intensity", False otherwise.
"""
int_vector = intensities
... |
def remove_title(text):
"""
Removes the title of a document
:param text: text containing an article output from cleanhtml()
:return: text of the article without title
"""
index = text.find("\n\n")
if index != -1:
return text[index+2:]
else:
return text |
def _check_mergability(info_tuple_list, dependents, logger):
"""
Checks if entries of config files from dependents can be combined into a common dependency
info_tuple_list is a list of tuples (display_name, set_getter)
set_getter is a function that returns the set of dependents for the given base bundl... |
def validate_required(row, variable, metadata, formater,pre_checks=[]):
"""
:param row:
:param variable:
:param metadata:
:param formater:
:param pre_checks:
:return:
"""
errors=[]
for fun in pre_checks:
if fun(row,variable,metadata)==False:
return errors
... |
def nd_cross_variogram(x1, y2, x2, y1):
"""
Inner most calculation step of cross-variogram
This function is used in the inner most loop of `neighbour_diff_squared`.
Parameters
----------
x, y : np.array
Returns
-------
np.array
"""
res = (x1 - x2)*(y1 - y2)
return r... |
def is_instance(instance, expected_types):
"""Check instance type is in one of expected types.
:param instance: instance to check the type.
:param expected_types: types to check if instance type is in them.
:type expected_types: list of type
:returns: True if instance type is in expect_type... |
def reformat_author(research_id, authors: str) -> tuple:
"""
Given a string with a variable length of author/editor names, split into first/last fields. Handles name suffixes.
Returns a list of research IDs where organizations are listed instead of individuals.
Raises ValueError where author field is bl... |
def verify_handedness(hand_input: str) -> bool:
"""
A helper function to make verifying handedness strings easier
Parameters
----------
hand_input: str
The single letter handedness string to be verified.
Valid inputs are: 'l', 'r', 'a'
Returns
----------
bool: Returns t... |
def response_formatter_api_doquery(res):
"""Convert API_DoQuery response to usable format."""
if not res['table']['records']:
res['table']['records'] = {'record': None}
else:
if not isinstance(res['table']['records']['record'], list):
res['table']['records']['record'] = [res['tab... |
def str2hex(s):
"""
Convert a string to its hexadecimal representation.
See examples in :func:`hex2str`.
"""
r = ''
for c in s:
r += hex(ord(c))[2:]
return r |
def make_counts(items):
"""Return a dict of string constraint names to the count of their honorers."""
return {
f"{constraint.__class__.__name__}.{constraint.name}": len(tests)
for group_members in items.values()
for constraint, tests in group_members.items()
} |
def evaluate_config(rnd: int):
"""Return evaluation configuration dict for each round.
Perform five local evaluation steps on each client (i.e., use five
batches) during rounds one to three, then increase to ten local
evaluation steps.
"""
val_steps = 5 if rnd < 4 else 10
return {"val_steps... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.