content stringlengths 42 6.51k |
|---|
def mse_node(w_samples, y_sum, y_sq_sum):
"""Computes the variance of the labels in the node
Parameters
----------
w_samples : float
Weighted number of samples in the node
y_sum : float
Weighted sum of the label in the node
y_sq_sum : float
Weighted sum of the squared labels in the node
Returns
-------
output : float
Variance of the labels in the node
"""
return y_sq_sum / w_samples - (y_sum / w_samples) ** 2 |
def read_file(file_name, mode='r'):
""" read file content
"""
try:
with open(file_name, mode) as f:
content = f.read()
except Exception:
return None
return content |
def singlyfy_parameters(parameters):
"""
Makes a cgi-parsed parameter dictionary into a dict where the values that
are just a list of a single value, are converted to just that single value.
"""
for key, value in parameters.items():
if isinstance(value, (list, tuple)) and len(value) == 1:
parameters[key] = value[0]
return parameters |
def char_formatter(line):
"""
Returns the char for the special offers
"""
return ''.join([ch for ch in line if not ch.isdigit()]) |
def collate_metrics(keys):
"""Collect metrics from the first row of the table.
Args:
keys (List): Elements in the first row of the table.
Returns:
dict: A dict of metrics.
"""
used_metrics = dict()
for idx, key in enumerate(keys):
if key in ['Method', 'Download']:
continue
used_metrics[key] = idx
return used_metrics |
def is_prime(n):
"""Check if n is prime or not."""
if (n < 2):
return False
for i in range(2, n + 1):
if (i * i <= n and n % i == 0):
return False
return True |
def average_precision(gt, pred,maxnum=-1):
"""
Computes the average precision.
This function computes the average prescision at k between two lists of
items.
Parameters
----------
gt: set
A set of ground-truth elements (order doesn't matter)
pred: list
A list of predicted elements (order does matter)
Returns
-------
score: double
The average precision over the input lists
"""
if not gt:
return 0.0
score = 0.0
num_hits = 0.0
for i,p in enumerate(pred):
if maxnum!=-1 and i >=maxnum:
break
if p in gt and p not in pred[:i]:
num_hits += 1.0
score += num_hits / (i + 1.0)
if maxnum==-1:
maxnum=len(gt)
return score / max(1.0, min(len(gt),maxnum)) |
def patron_ref_builder(loan_pid, loan):
"""Return the $ref for given loan_pid."""
return {"ref": "{}".format(loan_pid)} |
def format_callback_to_string(callback, args=None, kwargs=None):
"""
Convert a callback, its arguments and keyword arguments to a string suitable for logging purposes
:param ~collections.abc.Callable,str callback:
The callback function
:param list,tuple args:
The callback arguments
:param dict kwargs:
The callback keyword arguments
:rtype: str
"""
if not isinstance(callback, str):
try:
callback_str = "{}(".format(callback.__qualname__)
except AttributeError:
callback_str = "{}(".format(callback.__name__)
else:
callback_str = "{}(".format(callback)
if args:
callback_str += ", ".join([repr(arg) for arg in args])
if kwargs:
callback_str += ", ".join(["{}={!r}".format(k, v) for (k, v) in kwargs.items()])
callback_str += ")"
return callback_str |
def GetSettingTemplate(setting):
"""Create the template that will resolve to a setting from xcom.
Args:
setting: (string) The name of the setting.
Returns:
A templated string that resolves to a setting from xcom.
"""
return ('{{ task_instance.xcom_pull(task_ids="generate_workflow_args"'
').%s }}') % (
setting) |
def binary_search_recursive(array: list, target: int) -> int:
"""
binary search using recursion
"""
if len(array) == 0:
return -1
mid = len(array) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
return binary_search_recursive(array[mid + 1:], target)
else:
return binary_search_recursive(array[:mid], target) |
def is_valid_ip_prefix(prefix, bits):
"""Returns True if *prefix* is a valid IPv4 or IPv6 address prefix.
*prefix* should be a number between 0 to *bits* length.
"""
try:
# Prefix should be a number
prefix = int(prefix)
except ValueError:
return False
# Prefix should be a number between 0 to *bits*
return 0 <= prefix <= bits |
def SecureStringsEqual( a, b ):
"""Returns the equivalent of 'a == b', but avoids content based short
circuiting to reduce the vulnerability to timing attacks."""
# Consistent timing matters more here than data type flexibility
if not ( isinstance( a, str ) and isinstance( b, str ) ):
raise TypeError( "inputs must be str instances" )
# We assume the length of the expected digest is public knowledge,
# thus this early return isn't leaking anything an attacker wouldn't
# already know
if len( a ) != len( b ):
return False
# We assume that integers in the bytes range are all cached,
# thus timing shouldn't vary much due to integer object creation
result = 0
for x, y in zip( a, b ):
result |= ord( x ) ^ ord( y )
return result == 0 |
def get_ethnicity(x):
""" returns the int value for the ordinal value ethnicity
"""
if x == 'White':
return 1
elif x == 'Black':
return 2
elif x == 'Native American':
return 3
elif x == 'Asian':
return 4
else:
return 0 |
def get_station(seedid):
"""Station name from seed id"""
st = seedid.rsplit('.', 2)[0]
if st.startswith('.'):
st = st[1:]
return st |
def _isFunction(v):
"""
A utility function to determine if the specified
value is a function.
"""
if v==None:
return False
return hasattr(v, "__call__") |
def get_scalar(default_value, init_value = 0.0):
"""
Return scalar with a given default/fallback value.
"""
return_value = init_value
if default_value is None:
return return_value
return_value = default_value
return return_value |
def merge_dicts(*source_dicts):
"""Create a new dictionary and merge sources into it."""
target = {}
for source in source_dicts:
target.update(source)
return target |
def difference(n):
"""
This program will return differnce between square of sum and sum of square.
"""
sumOfSquare = 0
squareOfSum = 0
for i in range(n+1):
squareOfSum += i
sumOfSquare += i ** 2
return squareOfSum ** 2 - sumOfSquare |
def write_at_index(array, index, value):
"""Creates a copy of an array with the value at ``index`` set to
``value``. The array is extended if needed.
Parameters:
array (tuple): The input array
index (int): The index in the array to write to
value (value): The value to write
Returns:
A new tuple containing the modified array
"""
l = list(array)
extend = index - len(l) + 1
if extend > 0:
# FIXME: this could be a logic array, in which case we should use
# False instead of 0. But, using zero is not likely to cause problems.
l += [0] * extend
l[index] = value
return tuple(l) |
def mergesort(lst):
"""Perform merge sort algorithm."""
def divide(lst):
"""Divide."""
if len(lst) <= 1:
return lst
middle = len(lst) // 2
left = lst[:middle]
right = lst[middle:]
left = divide(left)
right = divide(right)
return merge(left, right)
def merge(left, right):
"""Conquer."""
result = []
while len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
while len(left) > 0:
result.append(left.pop(0))
while len(right) > 0:
result.append(right.pop(0))
return result
return divide(lst) |
def get_str_bytes_length(value: str) -> int:
"""
- source: https://stackoverflow.com/a/30686735/8445442
"""
return len(value.encode("utf-8")) |
def create_category_index(categories):
"""Creates dictionary of COCO compatible categories keyed by category id.
Args:
categories: a list of dicts, each of which has the following keys:
'id': (required) an integer id uniquely identifying this category.
'name': (required) string representing category name
e.g., 'cat', 'dog', 'pizza'.
Returns:
category_index: a dict containing the same entries as categories, but keyed
by the 'id' field of each category.
"""
category_index = {}
for cat in categories:
category_index[cat['id']] = cat
return category_index |
def is_cjmp(block):
"""Verify whether the block contains conditional jump.
Args:
block (list): a list of instructions (dict) belonging to one block
Returns:
bool: does the code block contain conditional jump?
"""
return (len(block[-1]["successors"]) == 2
and block[-1]["instruction"].name == "set_key") |
def openappend(file):
"""Open as append if exists, write if not."""
try:
output = open(file, 'a')
except Exception:
try:
output = open(file, 'w')
except Exception:
return 'error'
return output |
def findInter(next_event, event_atime, idx, end):
"""
Function:
findInter
Description:
The helper iterator function to find the intersection
Input:
next_event - available time based on the next event
event_atime - a list of available time based on events on date
idx - index of the current available time in the list
end - lenght of the list
Output:
- A list of available time for the date
"""
if idx == end:
return next_event
available_time = []
for at in event_atime[idx]:
for nt in next_event:
# If no intersection between event and favored time
if at.get('start') >= nt.get('end'):
pass
if at.get('end') <= nt.get('start'):
pass
# If in between
if nt.get('start') <= at.get('start') < at.get('end') <= nt.get('end'):
free_start = at.get('start')
free_end = at.get('end')
f_time = {'start': free_start, 'end': free_end}
if f_time not in available_time:
available_time.append({'start': free_start, 'end': free_end})
if at.get('start') < nt.get('start') < nt.get('end') < at.get('end'):
free_start = nt.get('start')
free_end = nt.get('end')
f_time = {'start': free_start, 'end': free_end}
if f_time not in available_time:
available_time.append({'start': free_start, 'end': free_end})
# If overlap
if nt.get('start') <= at.get('start') < nt.get('end') <= at.get('end'):
free_start = at.get('start')
free_end = nt.get('end')
f_time = {'start': free_start, 'end': free_end}
if f_time not in available_time:
available_time.append({'start': free_start, 'end': free_end})
if at.get('start') <= nt.get('start') < at.get('end') <= nt.get('end'):
free_start = nt.get('start')
free_end = at.get('end')
f_time = {'start': free_start, 'end': free_end}
if f_time not in available_time:
available_time.append({'start': free_start, 'end': free_end})
return findInter(available_time, event_atime, idx + 1, end) |
def _format_price_str(price_string):
""" Takes a string on the format '17 000:-...' and returns it on the format '17000'. """
price_string = price_string.split(':')[0]
return price_string.replace(" ", "") |
def check_error(error_code):
"""Converts the UCLCHEM integer result flag to a simple messaging explaining what went wrong"
Args:
error_code (int): Error code returned by UCLCHEM models, the first element of the results list.
Returns:
str: Error message
"""
errors={
-1:"Parameter read failed. Likely due to a mispelled parameter name, compare your dictionary to the parameters docs.",
-2: "Physics intiialization failed. Often due to user chosing unacceptable parameters such as hot core masses or collapse modes that don't exist. Check the docs for your model function.",
-3: "Chemistry initialization failed",#this doesn't exist yet
-4: "Unrecoverable integrator error, DVODE failed to integrate the ODEs in a way that UCLCHEM could not fix. Run UCLCHEM tests to check your network works at all then try to see if bad parameter combination is at play.",
-5: "Too many integrator fails. DVODE failed to integrate the ODE and UCLCHEM repeatedly altered settings to try to make it pass but tried too many times without success so code aborted to stop infinite loop."
}
try:
return errors[error_code]
except:
raise ValueError(f"Unknown error code: {error_code}") |
def get_gcd(x, y):
"""Calculate the greatest common divisor of two numbers."""
if y > x:
x, y = y, x
r = x % y
if r == 0:
return y
else:
result = get_gcd(y, r)
return result |
def _norm(x, max_v, min_v):
""" we assume max_v > 0 & max_v > min_v """
return (x-min_v)/(max_v-min_v) |
def inverse_linked_list(list_to_inverse, next_node_property_name="next"):
"""
A linked list inversor. No new nodes are created.
@param list_to_inverse: The linked list to inverse.
@param next_node_property_name: The name of property pointing to the next
node.
@return: The head of the inversed list.
"""
source_current_node = list_to_inverse
dest_head = None
while source_current_node:
old_source_head_next = getattr(source_current_node,
next_node_property_name)
setattr(source_current_node, next_node_property_name, dest_head)
dest_head = source_current_node
source_current_node = old_source_head_next
return dest_head |
def handle_exception(error: Exception):
"""When an unhandled exception is raised."""
message = "Error: " + getattr(error, 'message', str(error))
return {'message': message}, getattr(error, 'code', 500) |
def input_parameter_name(name, var_pos):
"""Generate parameter name for using as template input parameter names
in Argo YAML. For example, the parameter name "message" in the
container template print-message in
https://github.com/argoproj/argo/tree/master/examples#output-parameters.
"""
return "para-%s-%s" % (name, var_pos) |
def youngs_modulus(youngs_modulus):
"""
Defines the material properties for a linear-elastic hydrogel (such as Matrigel) hydrogel with a poission ratio of 0.25 (see [Steinwachs,2015], in this case Youngsmodulus equals K_0/6).
Args:
youngs_modulus(float) : Young's modulus of the material in Pascal for SAENO Simulation (see [Steinwachs,2015])
"""
return {'K_0': youngs_modulus*6, 'D_0': 1e30, 'L_S': 1e30, 'D_S': 1e30} |
def condensate_abovedew(Bg, Bgi, Gp, Gpi):
"""
Calculate the parameters for material balance plot of gas-condensate reservoirs
above dewpoint pressure
Input:
array: Bg, Gp
float: initial Bg, initial Gp
Output: F (array), Eg (array)
"""
Eg = Bg - Bgi
F = Bg * (Gp - Gpi)
return (F, Eg) |
def capture(func):
"""Return the printed output of func().
``func`` should be a function without arguments that produces output with
print statements.
>>> from sympy.utilities.iterables import capture
>>> from sympy import pprint
>>> from sympy.abc import x
>>> def foo():
... print('hello world!')
...
>>> 'hello' in capture(foo) # foo, not foo()
True
>>> capture(lambda: pprint(2/x))
'2\\n-\\nx\\n'
"""
from io import StringIO
import sys
stdout = sys.stdout
sys.stdout = file = StringIO()
try:
func()
finally:
sys.stdout = stdout
return file.getvalue() |
def basic_pyxll_function_1(x, y, z):
"""returns (x * y) ** z """
return (x * y) ** z |
def contains_sublist(list, sublist):
"""Return whether the given list contains the given sublist."""
def heads_match(list, sublist):
if sublist == ():
return True
elif list == ():
return False
else:
head, tail = list
subhead, subtail = sublist
if head == subhead:
return heads_match(tail, subtail)
else:
return False
if sublist == ():
return True
elif list == ():
return False
else:
match = heads_match(list, sublist)
if match:
return True
else:
head, tail = list
return contains_sublist(tail, sublist) |
def filter_opt(opt):
"""Remove ``None`` values from a dictionary."""
return [k for k, v in opt.items() if v] |
def common_get(list_header):
"""
:param list_header: list of training & testing headers
:return: common header
"""
golden_fea = ["F116", "F115", "F117", "F120", "F123", "F110", "F105", "F68", "F101", "F104", "F65", "F22",
" F94", "F71", "F72", "F25", "F3-", "F15", "F126", "F41", "F77"]
# mentioned in Dr. Wang's paper: Commonly-selected features (RQ1)
golden_fea.append("category")
golden_list = []
count_list = []
for header in list_header:
golden = []
count = 0
for i in header:
if i.startswith(tuple(golden_fea)):
count += 1
golden.append(i)
# print("number of golden fea:", count)
count_list.append(count)
golden_list.append(golden)
common = set(golden_list[0])
for s in golden_list[1:]:
common.intersection_update(s)
return common |
def anagram_solution_4(words):
"""
Count and Compare Complexity O(n)
Although the last solution was able to run in linear time,
it could only do so by using additional storage to keep the two lists of character counts.
In other words, this algorithm sacrificed space in order to gain time.
:param words: Tuple
:return: bool
"""
s1, s2 = words
c1 = [0] * 26
c2 = [0] * 26
for i in range(len(s1)):
pos = ord(s1[i]) - ord("a")
c1[pos] = c1[pos] + 1
for i in range(len(s2)):
pos = ord(s2[i]) - ord("a")
c2[pos] = c2[pos] + 1
j = 0
still_ok = True
while j < 26 and still_ok:
if c1[j] == c2[j]:
j = j + 1
else:
still_ok = False
return still_ok |
def split_and_join(line: str) -> str:
"""
>>> split_and_join('this is a string')
'this-is-a-string'
"""
return "-".join(line.split()) |
def expand_dict(init_dict):
"""
Expand dict keys to full names
:param init_dict: Initial dict
:type: dict
:return: Dictionary with fully expanded key names
:rtype: dict
"""
# Match dict for print output in human readable format
m = {'h': 'health', 's': 'status', 'ow': 'owner', 'owp': 'owner-preferred', 't': 'temperature',
'ts': 'temperature-status', 'cj': 'current-job', 'poh': 'power-on-hours', 'rs': 'redundancy-status',
'fw': 'firmware-version', 'sp': 'speed', 'ps': 'port-status', 'ss': 'sfp-status',
'fh': 'flash-health', 'fs': 'flash-status', '12v': 'power-12v', '5v': 'power-5v',
'33v': 'power-33v', '12i': 'power-12i', '5i': 'power-5i', 'io': 'iops', 'cpu': 'cpu-load',
'cjp': 'current-job-completion'
}
result_dict = {}
for compid, metrics in init_dict.items():
h_metrics = {}
for key in metrics.keys():
h_metrics[m[key]] = metrics[key]
result_dict[compid] = h_metrics
return result_dict |
def ipv4_address_validator(addr):
"""
Regex to validate an ipv4 address.
Checks if each octet is in range 0-255.
Returns True/False
"""
import re
pattern = re.compile(
r"^([1]?\d?\d|2[0-4]\d|25[0-5])\.([1]?\d?\d|2[0-4]\d|25[0-5])\.([1]?\d?\d|2[0-4]\d|25[0-5])\.([1]?\d?\d|2[0-4]\d|25[0-5])$"
)
if pattern.fullmatch(str(addr).strip().strip("\n")):
return True
else:
return False |
def find_odd_pair_product(someList=None):
"""
Find pair of integers in list whose product is odd,
and returns a list of tuples, where a tuple is made up
of both integers whose product is odd.
:param someList: List to find pairs within.
:return: List of pair-tuples.
"""
listPair = []
if someList is None:
someList = []
if len(someList) == 0:
return []
for i in range(len(someList)):
for j in range(1, len(someList), 1):
if (i * j) % 2 == 1:
listPair.append((i, j))
return listPair |
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
reference: http://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def sign(number):
"""Returns the sign of a given number."""
if number != 0:
return number / abs(number)
else:
return 0 |
def get_duplicates(setlist):
"""
Takes a list of sets, and returns a set of items that are found in
more than one set in the list
"""
duplicates = set()
for i, myset in enumerate(setlist):
othersets = set().union(*setlist[i+1:])
duplicates.update(myset & othersets)
return duplicates |
def reference_swap(my_dict: dict) -> dict:
"""
swap keys with values, note values must be immutable
"""
return {v: k for k, v in my_dict.items()} |
def single_v_L(v_L0, L):
"""
Calculates velocity of a single-phase flow at the given position L along
the wellbore. See the first equation of the system.
Args:
v_L0 (float) - boundary condition for velocity. Can assume any positive
value.
Returns:
float: the return value (flow velocity). Can assume any positive value;
normaly should be equal to the function's argument.
"""
v_L = v_L0
return(v_L) |
def static_url(context, static_file_path):
"""Filter for generating urls for static files.
NOTE: you'll need to set app['static_root_url'] to be used as
the root for the urls returned.
Usage:
{{ 'styles.css'|static }} might become
"/static/styles.css" or "http://mycdn.example.com/styles.css"
:param context: jinja2 context
:param static_file_path: path to static file under static route
:return: roughly just "<static_root_url>/<static_file_path>"
"""
app = context['app']
try:
static_url = app['static_root_url']
except KeyError:
raise RuntimeError(
"app does not define a static root url 'static_root_url', "
"you need to set the url root with "
"`app['static_root_url'] = '<static root>'`."
)
return '{static_url}/{file_path}'.format(
static_url=static_url.rstrip('/'),
file_path=static_file_path.lstrip('/'),
) |
def add_sign(number):
"""Return signed string:
x -> '+x'
-x -> '-x'
0 -> '0'
"""
if number > 0:
return f'+{number}'
else:
return str(number) |
def normalise(matrix):
"""Normalises the agents' cumulative utilities.
Parameters
----------
matrix : list of list of int
The cumulative utilities obtained by the agents throughout.
Returns
-------
list of list of int
The normalised cumulative utilities (i.e., utility shares) obtained by
the agents throughout.
"""
totals = [ sum(line) for line in matrix ]
return [ list(map(lambda x: x/tot, line)) for line, tot in zip(matrix, totals) ] |
def flatten_lists(lists: list) -> list:
"""Removes nested lists"""
result = list()
for _list in lists:
_list = list(_list)
if _list != []:
result += _list
else:
continue
return result |
def sieve_eratosthenes(range_to):
"""
A Very efficient way to generate all prime numbers upto a number.
Space complexity: O(n)
Time complexity: O(n * log(logn))
n = the number upto which prime numbers are to be generated.
"""
range_to=int(range_to)
# creating a boolean list first
prime = [True for i in range(range_to + 1)]
p = 2
while (p * p <= range_to):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, range_to + 1, p):
prime[i] = False
p += 1
# return the list of primes
return [p for p in range(2, range_to + 1) if prime[p]] |
def timeElapsed(seconds, opts=None):
"""Time Elapsed
Returns seconds in a human readable format with several options to show/hide
hours/minutes/seconds
Arguments:
seconds (uint): The seconds to convert to ((HH:)mm:)ss
opts (dict): Optional flags:
show_minutes: default True
show_seconds: default True
show_zero_hours: default False
show_zero_minutes: default False
Returns:
str
"""
# Get the hours and remaining seconds
h, r = divmod(seconds, 3600)
# Get the minutes and seconds
m, s = divmod(r, 60)
# Generate the flags
bShowMinutes = not opts or 'show_minutes' not in opts or opts['show_minutes']
bShowSeconds = not opts or 'show_seconds' not in opts or opts['show_seconds']
bShowZeroHours = opts and 'show_zero_hours' in opts and opts['show_zero_hours']
bShowZeroMinutes = opts and 'show_zero_minutes' in opts and opts['show_zero_minutes']
# Init the list we'll turn into time
lTime = None
# If we have hours
if h:
# Start by adding hours
lTime = [str(h)]
# If we want to show minutes
if bShowMinutes:
lTime.append(m < 10 and ('0%d' % m) or str(m))
# If we want to show seconds (can't show seconds if no minutes)
if bShowSeconds:
lTime.append(s < 10 and ('0%d' % s) or str(s))
# Else, if we have minutes
elif m:
# Init the time
lTime = []
# If we want to show zero hours
if bShowZeroHours:
lTime.append('0')
# If we want to show minutes
if bShowMinutes:
lTime.append((bShowZeroHours and m < 10) and ('0%d' % m) or str(m))
# If we want to show seconds (can't show seconds if no minutes)
if bShowSeconds:
lTime.append(s < 10 and ('0%d' % s) or str(s))
# Else, we only have seconds
else:
# Init the time
lTime = []
# If we want to show zero hours
if bShowZeroHours:
lTime.extend(['0', '00'])
# Else, if we want to show zero minutes
elif bShowZeroMinutes:
lTime.append('0')
# If we want to show seconds
if bShowMinutes and bShowSeconds:
lTime.append(
((bShowZeroMinutes or bShowZeroHours) and s < 10) and \
('0%d' % s) or \
str(s)
)
# Put them all together and return
return ':'.join(lTime) |
def readDirective(s):
"""Reads a directive line from forcefield, itp, or rtp file."""
# Remove comments, then split normally
sline = s.split(';')[0].split()
if len(sline) == 3 and sline[0] == '[' and sline[2] == ']':
return sline[1]
else:
return '' |
def summation(num):
"""Return sum of 0 to num."""
x = [i for i in range(num + 1)]
return sum(x) |
def resource_config_is_unchanged_except_for_tags(original_config, new_config,
except_tags=[]):
""" Recursively compare if original_config is the same as new_config except
for the except_tags
"""
if type(original_config) is str:
if original_config != new_config:
print(original_config)
return False
elif type(original_config) is list:
for i in range(len(original_config)):
if not resource_config_is_unchanged_except_for_tags(
original_config[i], new_config[i], except_tags):
print(i, original_config[i])
return False
elif type(original_config) is dict:
for i in original_config:
if i not in new_config:
continue
if i not in except_tags:
if not resource_config_is_unchanged_except_for_tags(
original_config[i],
new_config[i],
except_tags):
print(i, original_config[i])
return False
return True |
def get_option_list(string, all_value='all'):
"""
Method to switch the string of value separated by a comma into a list.
If the value is 'all', keep all.
:param string: string to change
:param all_value: value to return if all used
:return: None if not set, all if all, list of value otherwise
"""
if not string or string == 'nan':
return None
elif string == 'all':
return all_value
else:
return string.split(',') |
def to_words(node):
"""Generates a word list from all paths starting from an internal node."""
if not node:
return ['']
return [(node[0] + word) for child in node[1] for word in to_words(child)] |
def get_delete_op(op_name):
""" Determine if we are dealing with a deletion operation.
Normally we just do the logic in the last return. However, we may want
special behavior for some types.
:param op_name: ctx.operation.name.split('.')[-1].
:return: bool
"""
return 'delete' == op_name |
def ix(dot,orb,spin):
"""
Converts indices to a single index
Parameters
----------
dot : int
Dot number
orb : int
Orbital number (0 for p- and 1 for p+)
spin : int
0 for spin down, 1 for spin up.
Returns
-------
int
"""
return 4*dot+2*orb+spin |
def url_filter(url_list: list) -> list:
"""Filters out URLs that are to be queried, skipping URLs that responded with 204 HTTP code.
Args:
url_list: List of URL with metadata dict object.
Returns:
List of URL with metadata dict object that need to be queried.
"""
ret_list = []
for cur_url in url_list:
if cur_url['status'] == 'pending' or cur_url['status'].startswith('fail'):
if 'http_code' in cur_url:
if cur_url['http_code'] != '204':
ret_list.append(cur_url)
else:
ret_list.append(cur_url)
return ret_list |
def auth_str_equal(provided, known):
"""Constant-time string comparison.
:params provided: the first string
:params known: the second string
:returns: True if the strings are equal.
This function takes two strings and compares them. It is intended to be
used when doing a comparison for authentication purposes to help guard
against timing attacks. When using the function for this purpose, always
provide the user-provided password as the first argument. The time this
function will take is always a factor of the length of this string.
"""
result = 0
p_len = len(provided)
k_len = len(known)
for i in range(p_len):
a = ord(provided[i]) if i < p_len else 0
b = ord(known[i]) if i < k_len else 0
result |= a ^ b
return (p_len == k_len) & (result == 0) |
def add(x, y, z=0):
"""Add two (or three) objects"""
return x + y + z |
def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float:
"""
Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
>>> rankine_to_fahrenheit(273.15)
-186.52
>>> rankine_to_fahrenheit(300)
-159.67
>>> rankine_to_fahrenheit("315.5")
-144.17
>>> rankine_to_fahrenheit("rankine")
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'rankine'
"""
return round(float(rankine) - 459.67, ndigits) |
def weighted_sum(predictions, weight=None):
"""Returns a weighted sum of the predictions
"""
return sum([prediction["prediction"] * prediction[weight] for
prediction in predictions]) |
def real_diff(diff):
"""
:param diff: The diff to check.
:type diff: str
:return: True if diff is real (starts with ' ')
:rtype: bool
"""
return not diff.startswith(' ') |
def super_digit(n: int) -> int:
"""Return the result of summing of a number's digits until 1 digit remains."""
ds = n % 9
if ds:
return ds
return 9 |
def make_general_csv_rows(general_csv_dict):
"""
Method for make list of metrics from general metrics dict.
Rows using in general metrics writer
:param general_csv_dict: dict with all metrics
:type general_csv_dict: dict
:return: all metrics as rows
:rtype: list
"""
rows = []
for key, value in general_csv_dict.items():
row = [key[0], key[1]]
row.extend(value)
rows.append(row)
return rows |
def hash(h, key):
"""Function leaves considerable overhead in the grid_detail views.
each element of the list results in two calls to this hash function.
Code there, and possible here, should be refactored.
"""
return h.get(key, {}) |
def up(user_version: int) -> str:
"""Return minimal up script SQL for testing."""
return f"""
BEGIN TRANSACTION;
PRAGMA user_version = {user_version};
CREATE TABLE Test (key PRIMARY KEY);
COMMIT;
""" |
def vertinds_faceinds(vertex_inds, faces):
""" Return indices of faces containing any of `vertex_inds`
Parameters
----------
vertex_inds : sequence
length N. Indices of vertices
faces : (F, 3) array-like
Faces given by indices of vertices for each of ``F`` faces
Returns
---------
in_inds : sequence
Indices of `faces` which contain any of `vertex_inds`
"""
in_inds = []
vertex_inds = set(vertex_inds)
for ind, face in enumerate(faces):
if vertex_inds.intersection(face):
in_inds.append(ind)
return in_inds |
def extract_label(label):
"""Get the layer number, name and shape from a string.
Parameters
----------
label: str
Specifies both the layer type, index and shape, e.g.
``'03Conv2D_3x32x32'``.
Returns
-------
: tuple[int, str, tuple]
- layer_num: The index of the layer in the network.
- name: The type of the layer.
- shape: The shape of the layer
"""
label = label.split('_')
layer_num = None
for i in range(max(4, len(label) - 2)):
if label[0][:i].isdigit():
layer_num = int(label[0][:i])
name = ''.join(s for s in label[0] if not s.isdigit())
if name[-1] == 'D':
name = name[:-1]
if len(label) > 1:
shape = tuple([int(s) for s in label[-1].split('x')])
else:
shape = ()
return layer_num, name, shape |
def binary_fn(gold, pred):
"""
if there is any member of gold that overlaps with no member of pred,
return 1
else
return 0
"""
fns = 0
for p in gold:
fn = True
for word in p:
for span in pred:
if word in span:
fn = False
if fn is True:
fns += 1
return fns |
def I(x, A, s, L):
"""I(x) is the initial condition, meaning t=0
x is a variable in space
A is the amplitude
s is the intersection
L is the length
To form a "triangle-shaped" initial condition we
return the value I(x) of the 1st linear function in the equation set for x less than s
return the value I(x) of the 2nd linear function in the equation set for x larger than s
"""
if x >= 0 and x <= s:
return A*x/s
if x >= s and x <= L:
return A*(L-x)/(L-s) |
def Windowize(windowSize, individual):
"""Reduce individual size by summing the number of mutations
in a window and replacing all values with that sum."""
reducedIndividual = [0]
j = 0
for i in range(len(individual)):
reducedIndividual[j] += individual[i]
if((i+1)%windowSize == 0 and (i+1) != len(individual)):
j += 1
reducedIndividual.append(0)
return reducedIndividual |
def escape_html(s, quote = True):
"""escape HTML"""
s = s.replace("&", "&").replace("<", "<") \
.replace(">", ">")
if quote: s = s.replace('"', """).replace("'", "'")
return s |
def rank_results(results):
"""Ranks the results of the hyperparam search, prints the ranks and returns them.
Args:
results (list): list of model configs and their scores.
Returns:
list: the results list reordered by performance.
"""
ranking = sorted(results, key=lambda k: k["score"], reverse=True)
for i, rank in enumerate(ranking):
print(f"{i+1}. {rank['name']}: {rank['score']}")
print("\n")
return ranking |
def sort_latency_keys(latency):
"""The FIO latency data has latency buckets and those are sorted ascending.
The milisecond data has a >=2000 bucket which cannot be sorted in a 'normal'
way, so it is just stuck on top. This function resturns a list of sorted keys.
"""
placeholder = ""
tmp = []
for item in latency:
if item == ">=2000":
placeholder = ">=2000"
else:
tmp.append(item)
tmp.sort(key=int)
if placeholder:
tmp.append(placeholder)
return tmp |
def capenergy(C,v):
"""
capenergy Function
A simple function to calculate the stored voltage (in Joules)
in a capacitor with a charged voltage.
Parameters
----------
C: float
Capacitance in Farads.
v: float
Voltage across capacitor.
Returns
-------
energy: float
Energy stored in capacitor (Joules).
"""
energy = 1/2 * C * v**2
return(energy) |
def maximumGap(arr):
"""
:type arr: List[int]
:rtype: int
"""
if len(arr) < 2:
return 0
min_v, max_v = min(arr), max(arr)
if max_v - min_v < 2:
return max_v - min_v
min_gap = max(1, (max_v - min_v) // (len(arr))) # The minimum possible gap
sentinel_min, sentinel_max = 2 ** 32 - 1, -1
buckets_min = [sentinel_min] * len(arr)
buckets_max = [sentinel_max] * len(arr)
for x in arr:
i = min((x - min_v) // min_gap, len(arr) - 1)
buckets_min[i] = min(buckets_min[i], x)
buckets_max[i] = max(buckets_max[i], x)
max_gap = 0
prev_max = buckets_max[0] # First gap is always non-empty
for i in range(1, len(arr)):
if buckets_min[i] == sentinel_min:
continue
max_gap = max(buckets_min[i] - prev_max, max_gap)
prev_max = buckets_max[i]
return max_gap |
def circ_supply(height: int, nano: bool = False) -> int:
"""
Circulating supply at given height, in ERG (or nanoERG).
"""
# Emission settings
initial_rate = 75
fixed_rate_blocks = 525600 - 1
epoch_length = 64800
step = 3
# At current height
completed_epochs = max(0, height - fixed_rate_blocks) // epoch_length
current_epoch = completed_epochs + min(1, completed_epochs)
blocks_in_current_epoch = max(0, height - fixed_rate_blocks) % epoch_length
current_rate = max(0, initial_rate - current_epoch * step)
# Components
fixed_period_cs = min(fixed_rate_blocks, height) * initial_rate
completed_epochs_cs = sum(
[
epoch_length * max(0, initial_rate - step * (i + 1))
for i in range(completed_epochs)
]
)
current_epoch_cs = blocks_in_current_epoch * current_rate
# Circulating supply
cs = fixed_period_cs + completed_epochs_cs + current_epoch_cs
if nano:
cs *= 10**9
return cs |
def nsplit(seq, n=2):
"""Split a sequence into pieces of length n
If the length of the sequence isn't a multiple of n, the rest is discarded.
Note that nsplit will strings into individual characters.
Examples:
>>> nsplit('aabbcc')
[('a', 'a'), ('b', 'b'), ('c', 'c')]
>>> nsplit('aabbcc',n=3)
[('a', 'a', 'b'), ('b', 'c', 'c')]
# Note that cc is discarded
>>> nsplit('aabbcc',n=4)
[('a', 'a', 'b', 'b')]
"""
return [xy for xy in zip(*[iter(seq)] * n)] |
def is_diagonal(A):
"""Tells whether a matrix is a diagonal matrix or not.
Args
----
A (compulsory)
A matrix.
Returns
-------
bool
True if the matrix is a diagonal matrix, False otherwise.
"""
for i in range(len(A)):
for j in range(len(A[0])):
try:
if i != j and A[i][j] != 0:
return False
except IndexError: #Would happen if matrix is not square.
return False
return True |
def parse_visitor_score(d):
""" Used to parse score of visiting team.
"""
string_value = d.get("uitslag", " 0- 0")
(_, v) = string_value.replace(" ", "").split("-")
return int(v) |
def strip_namespace(tag_name):
"""
Strip all namespaces or namespace prefixes if present in an XML tag name .
For example:
>>> tag_name = '{http://maven.apache.org/POM/4.0.0}geronimo.osgi.export.pkg'
>>> expected = 'geronimo.osgi.export.pkg'
>>> assert expected == strip_namespace(tag_name)
"""
head, brace, tail = tag_name.rpartition('}')
return tail if brace else head |
def school2nation(id_num):
"""
Takes school id, returns nation id of the school.
"""
if id_num < 97100000:
return id_num // 100000 * 10000
if id_num < 97200000:
return 7240000
if id_num < 97400000:
return 8400000
return 320100 |
def einstein_a(freq,line_str,g_up):
"""
Einstein A from line_str (S_g mu_g^2), freq (MHz) and g_up, as
per eq. 6 in
www.astro.uni-koeln.de/site/vorhersagen/catalog/main_catalog.shtml
"""
return 1.16395e-20 * freq**3 * line_str / g_up |
def tap(value, interceptor):
"""Invokes `interceptor` with the `value` as the first argument and then
returns `value`. The purpose of this method is to "tap into" a method chain
in order to perform operations on intermediate results within the chain.
Args:
value (mixed): Current value of chain operation.
interceptor (function): Function called on `value`.
Returns:
mixed: `value` after `interceptor` call.
Example:
>>> data = []
>>> def log(value): data.append(value)
>>> chain([1, 2, 3, 4]).map(lambda x: x * 2).tap(log).value()
[2, 4, 6, 8]
>>> data
[[2, 4, 6, 8]]
.. versionadded:: 1.0.0
"""
interceptor(value)
return value |
def get_weight_shapes3(num_inputs, layer_sizes, num_outputs, m_trainable_arr, b_trainable_arr):
"""
see calc_num_weights3 for relevant of suffix
"""
weight_shapes = []
input_size = num_inputs
for i, layer in enumerate(layer_sizes):
if m_trainable_arr[i]:
weight_shapes.append((input_size, layer))
if b_trainable_arr[i]:
weight_shapes.append((layer,))
input_size = layer
if m_trainable_arr[-1]:
weight_shapes.append((input_size, num_outputs))
if b_trainable_arr[-1]:
weight_shapes.append((num_outputs,))
return weight_shapes |
def slash_count(l):
"""Check the slash count"""
l= str(l)
if l.count('/')<5:
return 0
elif l.count('/')>=5 and l.count('/')<=7:
return 2
else:
return 1 |
def is_number(s):
"""Is this the right way for checking a number.
Maybe there is a better pythonic way :-)"""
try:
int(s)
return True
except TypeError:
pass
except ValueError:
pass
return False |
def loess_abstract(estimator, threshold, param, length, migration_time, utilization):
""" The abstract Loess algorithm.
:param estimator: A parameter estimation function.
:type estimator: function
:param threshold: The CPU utilization threshold.
:type threshold: float
:param param: The safety parameter.
:type param: float
:param length: The required length of the utilization history.
:type length: int
:param migration_time: The VM migration time in time steps.
:type migration_time: float
:param utilization: The utilization history to analize.
:type utilization: list(float)
:return: A decision of whether the host is overloaded.
:rtype: bool
"""
if len(utilization) < length:
return False
estimates = estimator(utilization[-length:])
prediction = (estimates[0] + estimates[1] * (length + migration_time))
return param * prediction >= threshold |
def firmware_version_at_least(fw_version, major, minor):
"""
Returns True if the firmware version is equal to or above the provided
major and minor values.
"""
if fw_version['major'] > major:
return True
if fw_version['major'] == major and fw_version['minor'] >= minor:
return True
return False |
def int_or_none(string):
"""Return the string as Integer or return None."""
try:
return int(string)
except:
return None |
def getColumnTitle(min='-inf', max='+inf'):
"""
Human readable column titles
"""
if str(min) == '-inf' and str(max) == '+inf':
return 'Total'
elif str(min) == '-inf':
return 'Up to ' + '{0:,}'.format(max)
elif str(max) == '+inf':
return 'From ' + '{0:,}'.format(min)
elif min == max:
return '{0:,}'.format(min)
else:
return '{0:,}'.format(min) + ' to ' + '{0:,}'.format(max) |
def is_interactive():
"""Detects if package is running interactively
https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook
Returns:
bool: True if session is interactive
"""
import __main__ as main
return not hasattr(main, '__file__') |
def _get_seeds_to_create_not_interpolate_indicator(dense_keys, options):
"""Get seeds for each dense index to mask not interpolated states."""
seeds = {
dense_key: next(options["solution_seed_iteration"]) for dense_key in dense_keys
}
return seeds |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.