content stringlengths 42 6.51k |
|---|
def positive_number_to_smt(number):
"""
Print a floating-point number in decimal notation (i.e., prevent scientific notation).
This code is taken from https://stackoverflow.com/a/45604186.
:param number: floating-point number
:return: string in decimal notation
"""
number_as_two_strings = str(number).split('e')
if len(number_as_two_strings) == 1:
# no scientific notation needed
return number_as_two_strings[0]
base = float(number_as_two_strings[0])
exponent = int(number_as_two_strings[1])
result = ''
if int(exponent) > 0:
result += str(base).replace('.', '')
result += ''.join(['0' for _ in range(0, abs(exponent - len(str(base).split('.')[1])))])
elif int(exponent) < 0:
result += '0.'
result += ''.join(['0' for _ in range(0, abs(exponent) - 1)])
result += str(base).replace('.', '')
return result |
def is_pangram(sentence):
"""
return true if 'sentence' is an pangram
"""
sentence = sentence.lower()
return all(sentence.find(c) != -1 for c in 'abcdefghijklmnopqrstuvwxyz') |
def err(error_dictionary):
"""
Formats the error response as wanted by the Flask app
:param error_dictionary: name of the error dictionary
:return: tuple of error message and error number
"""
return {'error': error_dictionary['message']}, error_dictionary['code'] |
def toHex(val):
"""Converts the given value (0-255) into its hexadecimal representation"""
hex = "0123456789abcdef"
return hex[int(val / 16)] + hex[int(val - int(val / 16) * 16)] |
def bezier_cubic(p0, p1, p2, p3, t):
"""returns a position on bezier curve defined by 4 points at t"""
return (1-t)**3*p0 + 3*(1-t)**2*t*p1 + 3*(1-t)*t**2*p2 + t**3*p3 |
def escape_path(path):
"""
Escapes any characters that might be problematic in shell interactions.
:param path: The original path.
:return: A potentially modified version of the path with all problematic characters escaped.
"""
return path.replace("\\", "\\\\") |
def process_code_info(analysis, extensions):
"""Processes FileInformation objects into dictionary described below
Structure of the dictionary produced by this tool is:
{
<file_name>: {
"nloc": <file.nloc>,
"average_nloc": <file.average_NLOC>,
"average_tokens": <file.average_token>,
"average_ccn": <file.average_CCN>,
<function_name>: {
"nloc": <FunctionInfo.nloc>,
"ccn": <FunctionInfo.cyclomatic_complexity>,
"tokens": <FunctionInfo.token_count>,
"parameters": <FunctionInfo.parameter_count>,
"start_line": <FunctionInfo.start_line>,
"end_line": <FunctionInfo.end_line>,
"length": <FunctionInfo.length>
}
# functions can then be repeated until all are included
}
}
"""
data_dict= {}
for module_info in analysis:
data_dict[module_info.filename] = {}
file_name = module_info.filename
data_dict[file_name]["nloc"] = module_info.nloc
data_dict[file_name]["average_nloc"] = module_info.average_NLOC
data_dict[file_name]["average_tokens"] = module_info.average_token
data_dict[file_name]["average_ccn"] = module_info.average_CCN
for extension in extensions:
if hasattr(extension, 'reduce'):
extension.reduce(module_info)
if module_info:
#all_functions.append(module_info)
for fun in module_info.function_list:
name1 = module_info.filename
name2 = fun.name
data_dict[name1][name2] = {}
data_dict[name1][name2]["nloc"] = fun.nloc
data_dict[name1][name2]["ccn"] = fun.cyclomatic_complexity
data_dict[name1][name2]["tokens"] = fun.token_count
data_dict[name1][name2]["parameters"] = fun.parameter_count
data_dict[name1][name2]["start_line"] = fun.start_line
data_dict[name1][name2]["end_line"] = fun.end_line
data_dict[name1][name2]["length"] = fun.length
return data_dict |
def pad(lst, length, padding=' '):
"""
Pad a list up to length with padding
"""
return lst+[padding]*(length-len(lst)) |
def _jinja2_filter_storage_percent_class(value):
"""Formats the storage percentage class for templates"""
value = int(value[:-1])
if value < 95:
return "progress-bar"
elif value < 99:
return "progress-bar progress-bar-warning"
return "progress-bar progress-bar-danger" |
def subtractL(a, b, strict = True): # Multiset a - b.
""" Returns a new list: a - b. """
a = a[:]
for x in b:
try:
a.remove(x)
except ValueError as err:
if strict:
raise err
return a |
def ordenar_extraterrestre(desordenadas, orden_alfabeto):
"""Orders a list of words based on custom alphabet order"""
ordenada = sorted(
desordenadas, key=lambda word: [orden_alfabeto.index(char) for char in word]
)
return ordenada |
def _remove(target, delete):
"""
Removes fields from the target.
:param target: the JSON schema to remove fields from.
:param delete: the JSON schema fields to remove
:return: the target minus the delete fields.
"""
for k, v in delete.items():
dv = target.get(k)
if dv is not None:
if k == 'required':
for req in v:
target['properties'].pop(req, None)
target[k] = [i for i in target[k] if i not in v] # quadratic performance, optimize
elif isinstance(v, dict):
target[k] = _remove(dv, v)
elif isinstance(v, list):
target[k] = [i for i in dv if i not in v] # quadratic performance, optimize
return target |
def trim_envelope(env):
"""Trim envelope to global extents
"""
# clip extents if they are outside global bounding box
for c in range(len(env)):
if env[c][0] < -180:
env[c][0] = -180
elif env[c][0] > 180:
env[c][0] = 180
if env[c][1] < -90:
env[c][1] = -90
elif env[c][1] > 90:
env[c][1] = 90
return env |
def c_to_f(temp):
"""
Converts Celsius to Fahrenheit.
"""
return temp * 9/5 + 32 |
def make_string(seq):
"""
Don't throw an exception when given an out of range character.
"""
string = ''
for c in seq:
# Screen out non-printing characters.
try:
if 32 >= c < 256:
string += chr(c)
except TypeError:
pass
# If no printing chars
if not string:
return str(seq)
return string |
def check_unique_name(first_letters, count, name, unique_list, suffix=False):
"""Making sure new_name does not already exist
Args:
first_letters (str): string at the beginning of the name, giving a hint
on what the variable is.
count (int): increment to create a unique id in the name.
name (str): name that was just created. To be verified that it is unique
in this function.
unique_list (list): list where unique names are stored.
suffix (bool):
Returns:
new_name (str): name that is unique
"""
if suffix:
while name in unique_list:
count += 1
end_count = "%03d" % count
name = name[:-3] + end_count
else:
while name in unique_list:
count += 1
end_count = "%06d" % count
name = first_letters + "_" + end_count
return name, count |
def ssXXsuffix( i ):
"""Turns an integer into an ssXX ending between .ss01 and .ss20, e.g. 5 -> '.ss05'."""
if i < 1:
i = 1
elif i > 20:
i = 20
return ".ss%0.2d" % i |
def round_down(num,divisor):
"""round_down rows the value down by a divisor value.
Args:
num (int): An integer.
divisor (int): A number to divise by.
Returns:
[int]: A rounded down value byt he divisor.
"""
return num - (num%divisor) |
def add(A, B):
"""
Just writing this comment because it will pop up when asked for help
"""
C=A+B
return C |
def is_html_needed(user_agent):
"""
Basing on `user_agent`, return whether it needs HTML or ANSI
"""
plaintext_clients = ['curl', 'wget', 'fetch', 'httpie', 'lwp-request', 'python-requests']
if any([x in user_agent for x in plaintext_clients]):
return False
return True |
def QCheck(num):
"""Do a quick check if there is an even number in the set...at some point it will be an even number in rotation"""
numstr = str(num)
for i in range(len(numstr)):
if int(numstr[i]) % 2 == 0:
return False
if int(numstr[i]) % 5 == 0:
return False
return True |
def decode(encoded):
""""Take a JSOG-encoded JSON structure and create a new structure which re-links all the references. The return value will
not have any @id or @ref fields"""
# This works differently from the JavaScript and Ruby versions. Python dicts are unordered, so
# we can't be certain to see associated @ids before @refs. Instead we will make two passes,
# the first builds the object graph and tracks @ids; the second actually replaces @ref references
# with the associated object.
# holds string id -> copied object with that id. in the first pass, it will leave @refs alone.
found = {}
def firstPassDecode(encoded):
def firstPassDecodeObject(encoded):
if '@ref' in encoded:
# first pass leaves these alone
return encoded
result = {}
if '@id' in encoded:
found[encoded['@id']] = result
for key, value in encoded.items():
if key != '@id':
result[key] = firstPassDecode(value)
return result
def firstPassDecodeArray(encoded):
return [firstPassDecode(value) for value in encoded]
if isinstance(encoded, list):
return firstPassDecodeArray(encoded)
elif isinstance(encoded, dict):
return firstPassDecodeObject(encoded)
else:
return encoded
def deref(withRefs):
if isinstance(withRefs, dict):
for key, value in withRefs.items():
if isinstance(value, dict) and '@ref' in value:
withRefs[key] = found[value['@ref']]
else:
deref(value)
elif isinstance(withRefs, list):
for value in withRefs:
deref(value)
firstPass = firstPassDecode(encoded)
deref(firstPass)
return firstPass |
def longest_common_substring(data):
"""
Return a longest common substring of a list of strings:
>>> longest_common_substring(["apricot", "rice", "cricket"])
'ric'
>>> longest_common_substring(["apricot", "banana"])
'a'
>>> longest_common_substring(["foo", "bar", "baz"])
''
>>> longest_common_substring(["", "foo"])
''
>>> longest_common_substring(["apricot"])
'apricot'
>>> longest_common_substring([])
''
See http://stackoverflow.com/questions/2892931/.
"""
if len(data) == 1:
return data[0]
if not data or len(data[0]) == 0:
return ''
substr = ''
for i in range(len(data[0])):
for j in range(len(data[0])-i+1):
if j > len(substr) and all(data[0][i:i+j] in x for x in data):
substr = data[0][i:i+j]
return substr |
def count_by(x, n):
""" Return a sequence of numbers counting by `x` `n` times. """
return range(x, x * n + 1, x) |
def isSol(res):
"""
Check if the string is of the type ai bj ck
"""
if not res or res[0] != 'a' or res[-1] != 'c':
return False
l = 0
r = len(res)-1
while res[l] == "a":
l+=1
while res[r] == "c":
r-=1
if r-l+1 <= 0:
return False
for x in res[l:r-l+1]:
if x != 'b':
return False
return True |
def jaccard(set1,set2):
""" Calculates Jaccard coefficient between two sets."""
if(len(set1) == 0 or len(set2) == 0):
return 0
return float(len(set1 & set2)) / len(set1 | set2) |
def get_sender_id(data: dict) -> str:
"""
:param data: receives facebook object
:return: User id which wrote a message, type -> str
"""
sender_id = data['entry'][0]['messaging'][0]['sender']['id']
return sender_id |
def altz_to_utctz_str(altz):
"""As above, but inverses the operation, returning a string that can be used
in commit objects"""
utci = -1 * int((altz / 3600)*100)
utcs = str(abs(utci))
utcs = "0"*(4-len(utcs)) + utcs
prefix = (utci < 0 and '-') or '+'
return prefix + utcs |
def remove_invalid_fields(field):
"""For a record definition, remove all the invalid fields, otherwise return itself
Column type is a dict of the form {name: str, type: str, mode: str, fields: str?}"""
if field.get('type', 'INVALID') == 'RECORD':
field['fields'] = [remove_invalid_fields(subfield) for subfield in field['fields'] if subfield.get('type', 'INVALID') != 'INVALID']
field['fields'] = [subfield for subfield in field['fields'] if subfield['type'] != 'RECORD' or subfield.get('fields', []) != []]
return field |
def log_dir_name(learning_rate, num_dense_layers,
num_dense_nodes, activation):
"""
Function to log traning progress so that can be viewed by TnesorBoard.
"""
# The dir-name for the TensorBoard log-dir.
s = "./19_logs/lr_{0:.0e}_layers_{1}_nodes_{2}_{3}/"
# Insert all the hyper-parameters in the dir-name.
log_dir = s.format(learning_rate,
num_dense_layers,
num_dense_nodes,
activation)
return log_dir |
def choose_pivot(list, length):
"""
This function choose a pivot from the list
The function check the first, middle and last elements of the list,
and return the middle of there values (not the smallest and not the biggest)
:param list: the unsorted list
:param len: the list length
:return the index of the pivot element :
"""
middle = int((length -1)/2)
if ( list[0]< max(list[middle], list[length -1]) and list[0] > min(list[middle], list[length -1]) ):
return 0
elif ( list[middle]< max(list[0], list[length -1]) and list[middle] > min(list[0], list[length -1]) ):
return middle
else:
return length - 1 |
def solution(A, B):
"""
https://app.codility.com/demo/results/trainingDJQ263-4J9/
:param A: weights
:param B: direction
0 represents a fish flowing upstream - 0 fish ------ left direction
1 represents a fish flowing downstream - 1 fish ------ right direction
:return:
"""
stay_alive = 0
stack = []
for index, current_weight in enumerate(A):
# left or upstream
if B[index] == 0:
# stack has downstream fish information
weight_down_stream = stack.pop() if stack else -1
while weight_down_stream != - 1 and weight_down_stream < current_weight:
# current fish weight is greater, it will check for all stack fish and keep killing
weight_down_stream = stack.pop() if stack else -1
if weight_down_stream == -1:
stay_alive += 1
else:
# stack fish killed the current weight fish
stack.append(weight_down_stream)
else:
# 1 right or downstream
stack.append(current_weight)
return len(stack) + stay_alive |
def rotate(password, rotate_type, *params):
"""Rotate password
- rotate left/right X steps - means that the whole string
should be rotated; for example, one right rotation would turn
abcd into dabc.
- rotate based on position of letter X - means that the whole string should
be rotated to the right based on the index of letter X (counting
from 0) as determined before this instruction does any rotations.
Once the index is determined, rotate the string to the right one time,
plus a number of times equal to that index, plus one additional time
if the index was at least 4.
"""
if isinstance(params[0], int):
steps = params[0]
else:
index = password.index(params[1])
steps = index + 1
if index >= 4:
steps += 1
if rotate_type != 'left':
steps = -steps
steps = steps % len(password)
return password[steps:] + password[:steps] |
def getSignedVal(num: int, bitSize: int):
"""
Return the signed value of the number.
:param num: unsigned integer value
:param bitSize: length of the value in bits
"""
mask = (2 ** bitSize) - 1
if num & (1 << (bitSize - 1)):
return num | ~mask
else:
return num & mask |
def get_system_name_mappings(column_data):
"""
Given a column_data dict, get dicts mapping the system_name
to the display name, and vice versa.
"""
system_name_to_display_name = {}
display_name_to_system_name = {}
for key, entry in column_data.items():
if entry.get("system_name", None) is not None:
system_name = entry.get("system_name")
else:
system_name = key
system_name_to_display_name[system_name] = key
display_name_to_system_name[key] = system_name
return system_name_to_display_name, display_name_to_system_name |
def nth(items, i):
"""
Get the nth item from an iterable.
Warning: It consumes from a generator.
:param items: an iterable
:return: the first in the iterable
"""
for j, item in enumerate(items):
if j == i:
return item |
def format_output(files_filtered):
"""
"""
return " ".join(files_filtered) |
def gate_boundaries(gate_map):
""" Return gate boundaries
Args:
gate_map (dict)
Returns:
gate_boundaries (dict)
"""
gate_boundaries = {}
for g in gate_map:
gate_boundaries[g] = (-2000, 2000)
return gate_boundaries |
def calc_freq(text: str, topics: dict) -> dict:
"""Returns dict of occurrences of keywords for each category"""
text = text.lower()
occurrences = {}
for subject in topics:
freq = 0
index = 0
for keyword in topics[subject]:
while text.find(keyword, index) != -1:
index = text.find(keyword, index) + len(keyword)
freq += 1
occurrences[subject] = freq
return occurrences |
def go_down_right(x: int, y: int) -> tuple:
"""
Go 1 unit in negative y-direction and 1 unit in positive x-direction
:param x: x-coordinate of the node
:param y: y-coordinate of the node
:return: new coordinates of the node after moving diagonally down-right
"""
return x - 1, y + 1 |
def property_mapping_to_dict(cs_data):
"""Converts the property mapping in config strategy data from an
array like [ {'source': 'string'}, {'target': 'string'} ] to
a dict with { 'source-string': 'target-string', ... }.
"""
property_mapping_arr = cs_data['properties']['mapping']
property_mapping = {}
for mapping_obj in property_mapping_arr:
source = mapping_obj['source']
target = mapping_obj['target']
if source in property_mapping:
property_mapping[source].append(target)
else:
property_mapping[source] = [target]
return property_mapping |
def selection_largest_first(lst):
"""Find largest element and move to end of list, sort from there."""
for i in range(len(lst) - 1, 0, -1):
max_val=0
for j in range(1, i + 1):
if lst[j] > lst[max_val]:
max_val = j
temp = lst[i]
lst[i] = lst[max_val]
lst[max_val] = temp
return lst |
def create_dict_from_guard_rows(col_dict):
"""Create a dictionary of lists from a dictionary of guard values
Parameters
----------
col_dict : `dict`
The dictionary with the guard values
Returns
-------
ret_dict : `dict`
The dictionary we created
"""
ret_dict = {}
for key in col_dict.keys():
ret_dict[key] = []
return ret_dict |
def aggregate(iterator, only_no_facts = False):
""" Aggregates the records of this iterator.
Returns a 3-tuple (dict, int, float) with predicate->time, count and total.
"""
predicates = dict()
count = 0
total = float(0)
for (pred, time, facts) in iterator:
if facts == 0 or not only_no_facts:
if not pred in predicates:
predicates[pred] = 0
predicates[pred] += time
count += 1
total += time
return (predicates, count, total) |
def sum_closest_to_zero(array):
"""
:param array: given integer array
:return: Two elements such that their sum is closest to zero.
Method: 1
Complexity: O(n)
"""
if len(array) == 0:
return 0
array = sorted(array)
min_left = left = 0
min_right = right = len(array) - 1
min_sum = max(array) * 2 + 1
while left < right:
total = array[left] + array[right]
if total == 0:
return array[left], array[right]
if abs(total) < abs(min_sum):
print(min_sum, array[left], array[right])
min_sum = total
min_left = left
min_right = right
print(min_sum)
elif total > 0:
right -= 1
else:
left += 1
return array[min_left], array[min_right] |
def recalc_level(level, exp, exp_change):
""" Recalculate level and EXP after exp_change. """
exp += exp_change
if exp >= 0:
required = 1000 * (level + 1)
while exp >= required:
level += 1
exp -= required
required += 1000
else:
while exp < 0 and level > -1:
exp += 1000 * level
level -= 1
return level, exp |
def frombin(v):
"""MSB to LSB binary form"""
return int("".join(map(str, v)), 2 ) |
def match_entry(x, name, exclude):
""" identify config devices in any line listed in config not containing vdev keyword """
return not any(substring in x for substring in (exclude + (name,))) |
def sanitize_name_for_disk(name: str):
"""
Removes illegal filename characters from a string.
:param name: String to clean.
:return: Name with illegal characters removed.
"""
return "".join(char for char in name if char not in "|<>:\"/?*\\") |
def center_id_from_filename(filename):
"""Given the name of a rollgen PDF output file, return the center_id embedded in that name"""
# Fortunately all filenames are of the format NNNNN_XXXXXX.pdf where NNNNN is the center id
# and everything else comes after the first underscore.
return int(filename[:filename.index('_')]) |
def _naive_B(x, k, i, t):
"""
Naive way to compute B-spline basis functions. Useful only for testing!
computes B(x; t[i],..., t[i+k+1])
"""
if k == 0:
return 1.0 if t[i] <= x < t[i+1] else 0.0
if t[i+k] == t[i]:
c1 = 0.0
else:
c1 = (x - t[i])/(t[i+k] - t[i]) * _naive_B(x, k-1, i, t)
if t[i+k+1] == t[i+1]:
c2 = 0.0
else:
c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * _naive_B(x, k-1, i+1, t)
return (c1 + c2) |
def mymap(val, in_min, in_max, out_min, out_max):
"""
Returns the value which was mapped between in_min and in_max,
but now mapped between out_min and out_max.
If value is outside of bounds, it will still be outside afterwards.
"""
return int((val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min) |
def calculate_precision_recall_F_metrics(algorithm_number, real_number, correct_number):
"""
Result: (precision, recall, F)
"""
if algorithm_number == 0:
precision = 0
else:
precision = float(correct_number) / algorithm_number
if real_number == correct_number: # 0 / 0
recall = 1
else:
recall = float(correct_number) / real_number
return (precision, recall,
2 * float(correct_number) / (real_number + algorithm_number)) |
def _starts_with_vowel(char) -> bool:
"""Test to see if string starts with a vowel
Args:
char: character or string
Returns:
bool True if the character is a vowel, False otherwise
Examples:
>>> _starts_with_vowel('a')
True
>>> _starts_with_vowel('b')
False
>>> _starts_with_vowel('cat')
False
>>> _starts_with_vowel('apple')
True
"""
if len(char) > 1:
char = char[0]
return char in 'aeiou' |
def _intTime(tStr):
"""
Converts a time given as a string containing a float into an integer representation.
"""
return int(float(tStr)) |
def fix_kw(kw):
"""Make sure the given dictionary may be used as a kw dict independently on
the python version and encoding of kw's keys."""
return dict([(str(k), v) for k, v in list(kw.items())]) |
def _str(uni):
"""
Make inbound a string
Encoding to utf-8 if needed
"""
try:
return str(uni)
except:
return uni.encode('utf-8') |
def _parse_content_type(content_type):
"""best efforts on pulling out the content type and encoding from Content-Type header"""
try:
content_type = content_type.strip()
except AttributeError:
pass
char_set = None
if content_type.strip():
splt = content_type.split(';')
content_type = splt[0]
try:
raw_char_set = splt[1].strip()
key, char_set = raw_char_set.split('=')
if key != 'charset':
char_set = None
except (IndexError, ValueError):
pass
return content_type, char_set |
def PrintToConsole(message):
"""User defined function printing to console."""
print(message)
return 1 |
def iterable(obj):
"""
Check obj if is iterable
:param obj: object
:return: boolean
"""
return hasattr(obj, "__iter__") |
def center_ranges(input_ranges):
"""Given a list of sequences, create a list of new sequences
which are all the same length, by repeating the element
on the ends of any sequences shorter than the max length.
If any of the sequences is empty, they must all be empty
or a ValueError is raised (since there is nothing to pad with).
"""
ranges = [tuple(r) for r in input_ranges]
maxlen = 0
empty = False
for rng in ranges:
if len(rng) > maxlen:
maxlen = len(rng)
elif len(rng) == 0:
empty = True
if empty and maxlen > 0:
raise ValueError(f'cannot center empty range: {repr(ranges)}')
for i in range(len(ranges)):
rng = ranges[i]
if len(rng) < maxlen:
pad_count = maxlen - len(rng)
left_pad = right_pad = pad_count // 2
if left_pad + right_pad < pad_count:
right_pad += 1
ranges[i] = ((rng[0],) * left_pad) + rng + ((rng[-1],) * right_pad)
return ranges |
def validate_lbmethod(s, loc, tokens):
"""Validate the load balancing method used for real servers"""
methods = ['gate', 'masq', 'ipip']
if tokens[0] in methods:
return tokens
else:
errmsg = "Loadbalancing method must be one of %s " % ', '.join(methods)
raise ParseFatalException(s, loc, errmsg) |
def ucfirst(string):
"""Return string with first letter in upper case."""
if len(string) < 2:
return string.upper()
else:
return string[:1].upper() + string[1:] |
def new_balance(atype,bal,dr,cr):
"""compute the new balance after transaction"""
if atype in ("E","L","i"):
return bal+cr-dr
if atype in ("A","e"):
return bal+dr-cr
raise ValueError("Bad account type") |
def mandel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
if (z.real*z.real + z.imag*z.imag) >= 4:
return i
return max_iters |
def list_of_langs(data):
"""Construct list of language codes from data."""
lang_codes = []
for lang_data in data:
lang_codes.append(lang_data.get('value'))
return lang_codes |
def _format_parser(x) -> list:
"""Utility parser formatter.
Parameters
----------
x
Unformated parsed list.
Returns
-------
:
Formatted parsed list.
"""
if isinstance(x, tuple):
return [x]
else:
return [a for item in x for a in _format_parser(item)] |
def epsilon(ab_eps, bb_eps):
""" Perform combining rule to get A+A epsilon parameter.
Output units are whatever those are of the input parameters.
:param ab_eps: A+B epsilon parameter
:type ab_eps: float
:param ab_eps: B+B epsilon parameter
:type ab_eps: float
:rtype: float
"""
if ab_eps is not None and bb_eps is not None:
aa_eps = ab_eps**2 / bb_eps
else:
aa_eps = None
return aa_eps |
def _remove_nones(obj):
"""Return a new object ommitting keys whose value is none."""
return {key: value for key, value in obj.items() if value is not None} |
def compute_coupling_ratio(alphabet1, alphabet2):
"""
Compute the amount of coupling between two alphabets.
@param alphabet1: First alphabet.
@type alphabet1: C{set} of L{Event}
@param alphabet2: Second alphabet.
@type alphabet2: C{set} of L{Event}
@return: Amount of coupling.
@rtype: C{float}
"""
num_common = float(sum(1 for evt in alphabet1 if evt in alphabet2))
total = float(len(alphabet1.union(alphabet2)))
return num_common / total |
def get_data(base_url):
"""
This just inserts a hardcoded introspection string for the baseurl.
"""
return [
{
"api_version": "v1",
"available_api_versions": {
"v1": base_url+"v1/",
},
"formats": [
"json",
],
"entry_types_by_format": {
"json": [
"structure",
"calculation"
],
},
"available_endpoints": [
"entry",
"all",
"info"
]
}
] |
def get_duplicates(list_):
"""Returns the duplicates in a list l."""
seen = {}
duplicates = []
for x in list_:
if x not in seen:
seen[x] = 1
else:
if seen[x] == 1:
duplicates.append(x)
seen[x] += 1
return duplicates |
def CGx(N2, Omega, k, l, m, u, f):
"""
Horizontal group speed in x-direction in a flow
"""
# K2 = k**2 + l**2 + m**2
cgx = ((k * m**2 * (N2 - f**2))/((k**2 + l**2 + m**2)**2 * Omega)) + u
return cgx |
def trim_runtime(seconds: float) -> float:
"""Round seconds (float) to the nearest millisecond."""
return round(seconds, 3) |
def epsilon2(arg1, arg2=1000):
"""Do epsilon2
Usage:
>>> epsilon2(10, 20)
-20
>>> epsilon2(30)
-980
"""
return arg1 - arg2 - 10 |
def range_check(low, high):
"""\
Verifies that that given range has a low lower than the high.
>>> range_check(10, 11)
(10.0, 11.0)
>>> range_check(6.4, 30)
(6.4, 30.0)
>>> try:
... range_check(7, 2)
... except ValueError as e:
... print(e)
low >= high
"""
low, high = float(low), float(high)
if low >= high:
raise ValueError('low >= high')
else:
return low, high |
def apply_mapping(row, mapping=None):
"""Apply the mapping to one row."""
if mapping:
for old, new in mapping:
row[new] = row.pop(old)
return row |
def get_models_from_body_message(body):
"""
Method to get model id, model blob id, model bucket from input rabbitmq
message.
:param body: rabbitmq message body
:type body: dict
:return: models ids, models blob ids, models, buckets
"""
model_id = []
models_blob_ids = []
models_buckets = []
for model_ids in body['Models']:
model_id.append(model_ids['Id'])
models_blob_ids.append(model_ids['Blob']['id'])
models_buckets.append(model_ids['Blob']['bucket'])
return model_id, models_blob_ids, models_buckets |
def normalize_string(string):
"""Removes excess spaces from string.
Returns:
String without excess spaces.
"""
if not string:
return ''
return ' '.join(string.split()) |
def calculate_tensor_size_after_convs(input_size: int, sizes: list, strides: list):
"""helper method to calculate output size of an input into a conv net consisting of conv layers with filter `sizes`
and `strides`"""
t = input_size
for size, stride in zip(sizes, strides):
t = int((t - size) / stride + 1)
return t |
def get_complement(sequence):
"""Get the complement of a `sequence` of nucleotides.
Returns a string with the complementary sequence of `sequence`.
If `sequence` is empty, an empty string is returned.
Examples
--------
>>> get_complement('AUGC')
'UACG'
"""
sequence_upper = sequence.upper()
comp = {'A':'U', 'C':'G', 'G':'C', 'T':'A', 'U':'A'}
compSEQ = ''
for i in sequence_upper:
compSEQ += comp[i]
return compSEQ |
def _select_features(example, feature_list=None):
"""Select a subset of features from the example dict."""
feature_list = feature_list or ["inputs", "targets"]
return {f: example[f] for f in feature_list if f in example} |
def TransformSplit(r, sep='/', undefined=''):
"""Splits a string by the value of sep.
Args:
r: A string.
sep: The separator value to use when splitting.
undefined: Returns this value if the result after splitting is empty.
Returns:
A new array containing the split components of the resource.
Example:
"a/b/c/d".split() returns ["a", "b", "c", "d"]
"""
if not r:
return undefined
try:
return r.split(sep)
except (AttributeError, TypeError, ValueError):
return undefined |
def load_marker(i):
"""
Provide marker via index
@param i: index
"""
markers = ["o", "v", "D", "s", "*", "d", "^", "x", "+"]
return markers[i % len(markers)] |
def isList( obj ):
"""
Returns a boolean whether or not 'obj' is of type 'list'.
"""
return isinstance( obj, list ) |
def first(iterable, default=None, key=None):
"""
Return the first truthy value of an iterable.
Shamelessly stolen from https://github.com/hynek/first
"""
if key is None:
for el in iterable:
if el:
return el
else:
for el in iterable:
if key(el):
return el
return default |
def client_scope(application, client_role):
"""
:return scope of policy for client role
"""
return {"client_roles": [{"name": client_role(), "client": application["client_id"]}]} |
def is_secure_port(port):
"""
Returns True if port is root-owned at *nix systems
"""
if port is not None:
return port < 1024
else:
return False |
def compute_all_multiples(of_number, below_number):
"""Compute all natural numbers, which are multiples of a natural number below a predefined number."""
# Register the list of said multiples.
multiples = []
for i in range(1, below_number):
if not i % of_number:
multiples.append(i)
return multiples |
def is_recoverable_error(status_code: int) -> bool:
"""
True if the passed status_code hints at a recoverable server error. I.e. The same request might
be successful at a later point in time.
"""
if status_code < 400:
# Not an error, therefore not a retrieable error.
return False
if status_code // 100 == 4:
# Request Timeout, Connection Closed Without Response, Client Closed Request
if status_code in [408, 444, 499]:
return True
else:
# If the error is on client side we shouldn't just repeat it, for the most part.
return False
elif status_code // 100 == 5:
# Not implemented, HTTP Version not supported, Variant also negoiates, Insufficient Storage,
# Loop Detected, Not Extended, Network Authentication Required
if status_code in [501, 505, 506, 507, 508, 510, 511]:
return False
else:
# In general server errors may be fixed later
return True
else:
raise ValueError(f"Not an Http status code indicating an error: {status_code}") |
def type_compliance(variable, *args):
""" Private: internal library function, not intended for public use. """
return_list = []
for arg in args:
if isinstance(variable, arg):
return_list.append(True)
else:
return_list.append(False)
return True if True in return_list else False |
def dict_list_eq(l1, l2):
"""Compare to lists of dictionaries for equality.
"""
sorted_l1 = sorted(sorted(d.items()) for d in l1)
sorted_l2 = sorted(sorted(d.items()) for d in l2)
return sorted_l1 == sorted_l2 |
def split_num(num, n):
"""
Divide num into m=min(n, num) elements x_1, ...., x_n, where x_1, ..., x_n >= 1 and max_{i,j} |x_i - x_j| <= 1
"""
n = min(num, n)
min_steps = num // n
splits = []
for i in range(n):
if i < num - min_steps * n:
splits.append(min_steps + 1)
else:
splits.append(min_steps)
assert sum(splits) == num
return n, splits |
def _get_integer(value):
"""Converts a string into an integer.
Args:
value: string to convert.
Returns:
value converted into an integer, or 0 if conversion is not possible.
"""
try:
return int(value)
except ValueError:
return 0 |
def binarySearch(numList, left, right, target):
"""
Binary search for the range of number found in the exponential search algorithm
:param left: the first number in the range of number
:param right: the last number in the range of number
:param numList: a list of number sorted in ascending order
:param target: a number to be searched in the list of number
:return: index of target or None if target is not found
"""
if left > right:
return -1
mid = (left + right) // 2
if target == numList[mid]:
return mid
elif target < numList[mid]:
return binarySearch(numList, left, mid - 1, target)
else:
return binarySearch(numList, mid + 1, right, target) |
def RPL_ENDOFBANLIST(sender, receipient, message):
""" Reply Code 368 """
return "<" + sender + ">: " + message |
def u16leListToByteList(data):
"""Convert a halfword array into a byte array"""
byteData = []
for h in data:
byteData.extend([h & 0xff, (h >> 8) & 0xff])
return byteData |
def calc_emotion_feat(prev_emo, current_emo):
"""helper function to calculate the difference or the shift between two emotions"""
if prev_emo == current_emo:
return 0
else:
x = current_emo - prev_emo
return x |
def get_char_num(x):
"""
Convert signed integer to number in range 0 - 256
"""
return int((256+x)%256) |
def sizeof_address_blocks(blocks, usage):
"""return the consolidated size (offset == 0) for a list of address blocks"""
if blocks is None:
return 0
end = 0
for b in blocks:
if b.usage != usage:
continue
e = b.offset + b.size
if e > end:
end = e
# return the size
return end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.