content
stringlengths 42
6.51k
|
|---|
def sanitize_keys_in_dict(d: dict) -> dict:
"""Recursively sanitize keys in dict from str to int, float and None.
Args
d (dict):
d[name][charge][annotation]
"""
if not isinstance(d, dict):
return d
else:
new_d = dict()
for key, value in d.items():
try:
key = int(key)
except (ValueError, TypeError):
try:
key = float(key)
except (ValueError, TypeError):
if key == "null":
key = None
value = None if value == "null" else sanitize_keys_in_dict(value)
new_d[key] = value
return new_d
|
def change_dic_key(dic,old_key,new_key):
"""Change dictionary key with new key"""
dic[new_key] = dic.pop(old_key)
return dic
|
def get_spk_agent_one_hot_vec(context, agent_index_dict, max_n_agents):
"""
:param context: 1D: n_prev_sents, 2D: n_words
:param agent_index_dict: {agent id: agent index}
:param max_n_agents: the max num of agents that appear in the context (=n_prev_sents+1); int
:return: 1D: n_prev_sents, 2D: max_n_agents
"""
speaking_agent_one_hot_vector = []
for c in context:
vec = [0 for i in range(max_n_agents)]
speaker_id = c[1]
vec[agent_index_dict[speaker_id]] = 1
speaking_agent_one_hot_vector.append(vec)
return speaking_agent_one_hot_vector
|
def check_part_err(part, key_name):
"""chec part field"""
try:
return part[key_name]
except KeyError: #undefined field name
print("Error\t:wrong field\nCHECK!!!\n")
for field in part.items():
print(f"{field[0]:12}\t{field[1]}")
|
def remove_dups(arg_list):
"""
Method: remove_dups
remove duplicates in a list
Params:
arg_list
:: list
:: the list to be processed
"""
no_dups = []
for arg in arg_list:
if arg not in no_dups:
no_dups.append(arg)
return no_dups
|
def str_list(value):
"""Convert a literal comma separated string to a string list."""
if not value:
return []
return value.split(",")
|
def get_all_individuals_to_be_vaccinated_by_area(
vaccinated_compartments, non_vaccination_state, virus_states, area
):
"""Get sum of all names of species that have to be vaccinated.
Parameters
----------
vaccinated_compartments : list of strings
List of compartments from which individuals are vaccinated.
non_vaccination_state : str
Name of state indicates non-vaccinated individuals.
virus_states : list of strings
List containing the names of the virus types.
area : str
Name of the area.
Returns
-------
vaccinated_individuals : str
Sum of all names of species that have to be vaccinated.
"""
vaccinated_individuals = ""
for index_compartments in vaccinated_compartments:
for index_virus in virus_states:
for index_areas in [area]:
if index_compartments != "susceptible":
state = f"{index_compartments}_{index_areas}_{non_vaccination_state}_{index_virus}"
vaccinated_individuals = vaccinated_individuals + "+" + state
for index_areas in [area]:
state = f"susceptible_{index_areas}_{non_vaccination_state}"
vaccinated_individuals = vaccinated_individuals + "+" + state
return vaccinated_individuals
|
def pad_sents(sents, pad_token):
""" Pad list of sentences according to the longest sentence in the batch.
The paddings should be at the end of each sentence.
@param sents (list[list[str]]): list of sentences, where each sentence
is represented as a list of words
@param pad_token (str): padding token
@returns sents_padded (list[list[str]]): list of sentences where sentences shorter
than the max length sentence are padded out with the pad_token, such that
each sentences in the batch now has equal length.
"""
sents_padded = []
# Find max_length from input batch sentence
len_x = [len(x) for x in sents]
len_x.sort()
max_length = len_x[-1]
for sentence in sents:
new_sentence = sentence + [pad_token] * (max_length - len(sentence))
sents_padded.append(new_sentence)
return sents_padded
|
def fibo_memo(n, mem):
"""
top-down approach
"""
if n == 0:
return 0
if n == 1:
return 1
if mem[n] is not None:
return mem[n]
mem[n] = fibo_memo(n-1, mem) + fibo_memo(n-2, mem)
return mem[n]
|
def _pixel_addr(x, y):
"""Translate an x,y coordinate to a pixel index."""
if x > 8:
x = x - 8
y = 6 - (y + 8)
else:
x = 8 - x
return x * 16 + y
|
def adjust_factor(x, x_lims, b_lims=None):
"""
:param float x: current x value
:param float x_lims: box of x values to adjust
:param float b_lims: bathy adj at x_lims
:rtype: float
:returns: b = bathy adjustment
"""
if b_lims is None:
return 0
if x < x_lims[0] or x > x_lims[1]:
return 0
else:
value = b_lims[0]
slope = (b_lims[1]-b_lims[0]) / (x_lims[1]-x_lims[0])
value += (x-x_lims[0])*slope
return value
|
def recall_pos_conf(conf):
"""compute recall of the positive class"""
TN, FP, FN, TP = conf
if (TN + FP) == 0:
return float('nan')
return TP/float(TP+FN)
|
def select_login_fields(fields):
"""
Select field having highest probability for class ``field``.
:param dict fields: Nested dictionary containing label probabilities
for each form element.
:returns: (username field, password field, captcha field)
:rtype: tuple
"""
username_field = None
username_prob = 0
password_field = None
password_prob = 0
captcha_field = None
captcha_prob = 0
for field_name, labels in fields.items():
for label, prob in labels.items():
if label in ("username", "username or email") and prob > username_prob:
username_field = field_name
username_prob = prob
elif label == "password" and prob > password_prob:
password_field = field_name
password_prob = prob
elif label == "captcha" and prob > captcha_prob:
captcha_field = field_name
captcha_prob = prob
return username_field, password_field, captcha_field
|
def to_ms(microseconds):
"""
Converts microseconds to milliseconds.
"""
return microseconds / float(1000)
|
def darken_color(c):
"""
Darken a color.
Small utility function to compute the color for the border of
the problem name badges.
When no color is passed, a dark border is set.
"""
if not c:
return '#000' # black
r, g, b = int(c[1:3], 16), int(c[3:5], 16), int(c[5:], 16)
return '#{:0>6s}'.format(
hex(int(r * 0.5) << 16 | int(g * 0.5) << 8 | int(b * 0.5))[2:])
|
def find_k_8(n):
"""Exact solution for k = 4"""
if n == 1:
return 1
cycle, rem = divmod(n - 1, 4)
adjustment = cycle * 3 - 2
result = (pow(2, cycle * 4 - 2) + pow(2, adjustment)) * pow(2, rem)
return result
|
def findPassingDistances ( distances, threshold ):
"""
This function takes a list of distances and a threshold and returns all indices of
distances which pass the threshold, or -1 if no distances is below the threshold.
Parameters
----------
list : distances
The list of the distances to be searched.
float : threshold
The threshold below which any passing distance needs to be.
Returns
-------
list : indices
The indices of all passing distances or -1 if no distance is below the threshold.
"""
### Initialise variables
minInd = []
indCtr = 0
### Find all passing distances
for val in distances:
if val[0] < threshold:
minInd.append ( indCtr )
indCtr += 1
### Check for at least one
if len( minInd ) == 0:
minInd = -1
### Return the index
return ( minInd )
|
def _get_attention_sizes(resnet_size):
"""The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
"""
choices = {
18: [False, [False, True], [True, False], False],
34: [False, [False, True, True, False], False, False],
50: [False, [False, False, False, False], True, False],
101: [False, False, True, True],
152: [False, False, True, True],
200: [False, False, True, True]
}
try:
return choices[resnet_size]
except KeyError:
err = (
'Could not find layers for selected Resnet size.\n'
'Size received: {}; sizes allowed: {}.'.format(
resnet_size, choices.keys()))
raise ValueError(err)
|
def get_underline (title, underline_char):
""" Given a string and a character (a string of length 1,
although this is not enforced), return an "underline"
consisting of the character repeated the same length
as the title.
title had better not be None.
"""
return underline_char * len(title)
|
def bgdrat_point(aminrl, varat_1_iel, varat_2_iel, varat_3_iel):
"""Calculate required C/iel ratio for belowground decomposition.
When belowground material decomposes, its nutrient content is
compared to this ratio to check whether nutrient content is
sufficiently high to allow decomposition. This ratio is calculated at
each decomposition time step.
Parameters:
aminrl (float): mineral <iel> (N or P) in top soil layer, averaged
across decomposition time steps
varat_1_iel (float): parameter, maximum C/iel ratio
varat_2_iel (float): parameter, minimum C/iel ratio
varat_3_iel (float): parameter, amount of iel present when minimum
ratio applies
Returns:
bgdrat, the required C/iel ratio for decomposition
"""
if aminrl <= 0:
bgdrat = varat_1_iel
elif aminrl > varat_3_iel:
bgdrat = varat_2_iel
else:
bgdrat = (
(1. - aminrl / varat_3_iel) * (varat_1_iel - varat_2_iel) +
varat_2_iel)
return bgdrat
|
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5',\
'*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215',\
'*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215',\
'*35214*', '*41532*', '*2*1***'])
False
"""
for line in board:
if '?' in line:
return False
return True
|
def putblock(b):
"""Puts a block"""
print("PutBlock()")
return True
|
def base_canonical_coords_to_pyrobot_coords(xyt):
"""converts from canonical coords from to pyrobot coords."""
return [xyt[1], -xyt[0], xyt[2]]
|
def process_what_to_run_concepts(pairs_to_test):
"""Process concepts and pairs to test.
Args:
pairs_to_test: a list of concepts to be tested and a target (e.g,
[ ("target1", ["concept1", "concept2", "concept3"]),...])
Returns:
return pairs to test:
target1, concept1
target1, concept2
...
target2, concept1
target2, concept2
...
"""
pairs_for_sstesting = []
# prepare pairs for concpet vs random.
for pair in pairs_to_test:
for concept in pair[1]:
pairs_for_sstesting.append([pair[0], [concept]])
return pairs_for_sstesting
|
def non_decreasing(L):
"""Return True if list L is non-decreasing."""
return all(x <= y for x, y in zip(L, L[1:]))
|
def check(n):
""" check if number if of the form 1_2_3_4_5_6_7_8_9"""
n = str(n)
if len(n) != 17:
return False
else :
bit = 1
for i in range(17):
if i %2 == 0:
if n[i] != str(bit):
return False
bit += 1
return True
|
def IsInt(s):
"""
Is a string an integer number?
@return boolean
"""
try:
int(s)
return True
except ValueError:
return False
|
def get_true_shooting(points, fga, tpfga, fta):
"""
Calculates true shooting percentage.
:param int points: Points
:param int fga: Field goals attempted
:param int tpfga: Three point field goals attempted
:param int fta: Free throws attempted
:return: True shooting percentage
:rtype: float
"""
try:
ts = points / (2.0 * ((fga + tpfga) + 0.44 * fta))
except ZeroDivisionError:
ts = 0
return round(ts, 3)
|
def getProduct(row):
"""
Returns an array of the products of first element and the rest
of the elements in row
"""
temp = row.split('\t')
data = []
for i in temp[1:]:
data.append(float(temp[0])*float(i))
return data
|
def cyclic_subgroup(a):
"""The elements of the cyclic subgroup generated by point"""
G = []
t = a
while True:
G.append(t)
t = a+t
if t == a:
break
return G
|
def get_available_stuff(dim_length: int, useless_padding: int, box_length: int):
"""helper function of get available stuff for generate_crop_boxes
Args:
length (int): total length for height or width
useless_padding (int): useless padding along length
box_length (int): box length along this dim
"""
curr_idx = useless_padding
available_stuff = []
while curr_idx + box_length + useless_padding <= dim_length:
available_stuff.append(curr_idx)
curr_idx += box_length
return available_stuff
|
def parse_str(s):
"""Try to parse a string to int, then float, then bool, then leave alone"""
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
if s.lower() == 'true':
return True
if s.lower() == 'false':
return False
return s
|
def definition():
"""
Snapshot of 1 to 1 teaching. Cost is more important than group,
as changing a student's tutor destroys the old group.
Distinct from ss_1to1, as this is used for the list screen whilst the other
is used for finding differences.
"""
sql = """
select g.instance_id, g.cost_id, m.student_id, m.name, s.staff_id
FROM tt_ss_tgroup g
INNER JOIN tt_ss_membership m ON m.tgroup_id = g.tgroup_id AND g.instance_id = m.instance_id
INNER JOIN tt_ss_staffing s ON s.tgroup_id = g.tgroup_id AND g.instance_id = s.instance_id
WHERE g.tt_type_id = 3
"""
return sql
|
def calculate_largest_square_filled_space_optimized2(matrix):
"""
A method that calculates the largest square filled with only 1's of a given binary matrix (space-optimized 2/2).
Problem description: https://practice.geeksforgeeks.org/problems/largest-square-formed-in-a-matrix/0
time complexity: O(n*m)
space complexity: O(min(n,m))
Parameters
----------
matrix : int[[]]
a 2-dimensional list
Returns
-------
int
size of the largest square
"""
n = len(matrix)
assert n >= 1
m = len(matrix[0])
assert m >= 1
max_square_size = 0
if n < m:
arr = [
[0 for _ in range(n)],
[0 for _ in range(n)]
]
for j in range(m):
arr[0] = [e for e in arr[1]]
for i in range(n):
if matrix[i][j] == 0:
arr[1][i] = 0
else:
if j == 0 or i == 0:
arr[1][i] = 1
else:
arr[1][i] = min([
arr[0][i],
arr[1][i-1],
arr[0][i-1]
]) + 1
max_square_size = max(arr[1][i], max_square_size)
else:
arr = [
[0 for _ in range(m)],
[0 for _ in range(m)]
]
for i in range(n):
arr[0] = [e for e in arr[1]]
for j in range(m):
if matrix[i][j] == 0:
arr[1][j] = 0
else:
if i == 0 or j == 0:
arr[1][j] = 1
else:
arr[1][j] = min([
arr[0][j],
arr[1][j-1],
arr[0][j-1]
]) + 1
max_square_size = max(arr[1][j], max_square_size)
return max_square_size
|
def is_flat(obj):
"""Check whether list or tuple is flat, returns true if yes, false if nested."""
return not any(isinstance(x, (list, tuple)) for x in obj)
|
def parse_dot_key(data, key):
"""
Provide the element from the ``data`` dictionary defined by the ``key``.
The key may be a key path depicted by dot notation.
:param data: A dictionary
:param key: A dictionary key string that may be a key path depicted by dot
notation. For example "foo.bar".
:returns: The dictionary value from ``data`` associated to the ``key``.
"""
for key_part in key.split('.'):
data = data.get(key_part)
if data is None:
break
return data
|
def int_to_roman(inp):
"""
Convert an integer to Roman numerals.
"""
# stolen from
# https://code.activestate.com/recipes/81611-roman-numerals/
if not isinstance(inp, int):
raise TypeError("expected integer, got %s" % type(inp))
if inp == 0:
return "Z"
if not 0 < inp < 4000:
raise ValueError("Argument must be between 1 and 3999 (got %d)" % inp)
ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
nums = ("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
result = ""
for i in range(len(ints)):
count = int(inp / ints[i])
result += nums[i] * count
inp -= ints[i] * count
return result
|
def numero_case(x, y, cote):
"""
Trouver le numero de la case du pixel (x,y)
si le graph est en forme de damier noir et blanc et que
les cases sont numerotees par leur numero vertical et horizontal
en commencant par 0
"""
nv = int(x / cote)
nh = int(y / cote)
return nv, nh
|
def add_spaces_to_lines(count, string):
"""Adds a number of spaces to the start of each line
Doesn't add spaces to the first line, as it should already be
fully indented"""
all_lines = string.splitlines(True)
new_string = all_lines[0]
for i in range(1, len(all_lines)):
new_string += ' ' * count + all_lines[i]
return new_string
|
def extract_tests(api_response, defined_tests):
"""
Create and return a dict of test name to test data.
If api_response is None, return a dict with an empty dict.
api_response: the JSON response from the Proctor API in Python object form.
defined_tests: an iterable of test name strings defining the tests that
should be available to the user. Usually from Django settings.
"""
if api_response is None:
return {'tests': {}}
api_audit = api_response['audit']
api_tests = api_response['tests']
test_dict = {}
for test_name in defined_tests:
if test_name in api_tests:
test_dict[test_name] = api_tests[test_name]
else:
# For all valid tests, we use an empty dict.
# For tests NOT in the settings, access is an AttributeError.
# This helps enforce program correctness.
test_dict[test_name] = {}
return {'audit': api_audit, 'tests': test_dict}
|
def in_dict(key, dictionary):
"""
Inputs: key- the key to be checked for in the dictionary
dictionary- the dictionary the key will be searched in
Checks a dictionary to see if it contains a key. If it does, True is
returned; False is returned otherwise.
"""
keys = list(dictionary)
for each in keys:
if each == key:
return True
return False
|
def evaluate_example_targetid(goldtargets, prediction):
""" (Unlabeled) target evaluation.
"""
tp = fp = fn = 0.0
for target in goldtargets:
if target in prediction:
tp += 1
else:
fn += 1
for pred_target in prediction:
if pred_target not in goldtargets:
fp += 1
return [tp, fp, fn]
|
def _pairwise(true, pred):
"""Return numerators and denominators for precision and recall,
as well as size of symmetric difference, used in negative pairwise."""
p_num = r_num = len(true & pred)
p_den = len(pred)
r_den = len(true)
return p_num, p_den, r_num, r_den
|
def get_mod_from_id(mod_id, mod_list):
"""
Returns the mod for given mod or None if it isn't found.
Parameters
----------
mod_id : str
The mod identifier to look for
mod_list : list[DatRecord]
List of mods to search in (or dat file)
Returns
-------
DatRecord or None
Returns the mod if found, None otherwise
"""
for mod in mod_list:
if mod['Id'] == mod_id:
return mod
return None
|
def prefixify(d: dict, p: str):
"""Create dictionary with same values but with each key prefixed by `{p}_`."""
return {f'{p}_{k}': v for (k, v) in d.items()}
|
def get_output_between(output, first, second):
"""Gets part of the output generated by the node.js scripts between two string markers"""
start = output.find(first)
end = output.find(second)
return output[start + len(first) + 1:end - 1].decode("utf-8")
|
def lharmonicmean (inlist):
"""
Calculates the harmonic mean of the values in the passed list.
That is: n / (1/x1 + 1/x2 + ... + 1/xn). Assumes a '1D' list.
Usage: lharmonicmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + 1.0/item
return len(inlist) / sum
|
def _percent_str(percentages):
"""Convert percentages values into string representations"""
pstr = []
for percent in percentages:
if percent >= 0.1:
pstr.append('%.1f' %round(percent, 1)+' %')
elif percent >= 0.01:
pstr.append('%.2f' %round(percent, 2)+' %')
else:
pstr.append('%.3f' %round(percent, 3)+' %')
return pstr
|
def filter_response(response, access_levels_dict, accessible_datasets, user_levels, field2access, parent_key=None):
"""
Recursive function that parses the response of the beacon to filter out those fields that are
not accessible for the user (based on the access level).
:response: beacon response
:access_levels_dict: access levels dictionary created out of the yml file in /utils
:accessible_datasets: list of datasets accessible by the user (taking into account its privileges)
:user_levels: list of levels that the user has, i.e ['PUBLIC', 'REGISTERED']
:field2access: dictionary that maps the child_field name to its corresponding parent_field name in the access levels dict (i.e 'datasets' inside the parent 'beacon' maps to its parent name 'beaconDataset')
:parent_key: used inside de recursion to store the parent key of the dict we are in
"""
final_dict = {}
if isinstance(response, dict):
for key, val in response.items():
translated_key = field2access[key] if key in field2access.keys() else key
specific_access_levels_dict = access_levels_dict[parent_key] if parent_key else access_levels_dict
if translated_key not in access_levels_dict.keys() and translated_key not in specific_access_levels_dict.keys():
final_dict[key] = val
else:
# if (isinstance(val, dict) or isinstance(val, list)) and key != "info":
if (isinstance(val, dict) or isinstance(val, list)) and translated_key in access_levels_dict.keys():
parent_permission = True
self_permission = True if access_levels_dict[translated_key]["accessLevelSummary"] in user_levels else False
if parent_key:
parent_permission = True if access_levels_dict[parent_key][key] in user_levels else False
if self_permission and parent_permission:
final_dict[key] = filter_response(val, access_levels_dict, accessible_datasets, user_levels, field2access, translated_key)
else:
valid_level = access_levels_dict[parent_key][translated_key] if parent_key else access_levels_dict[translated_key]
if valid_level in user_levels:
final_dict[key] = val
elif isinstance(response, list):
filtered = []
for element in response:
if isinstance(element, dict):
datasetId = element.get("internalId")
if not datasetId or datasetId in accessible_datasets: # controlling specific access permission to show a dataset response
filtered.append(filter_response(element, access_levels_dict, accessible_datasets, user_levels, field2access, parent_key))
return filtered
return final_dict
|
def handle_request(request):
"""Handles the HTTP request."""
headers = request.split('\n')
filename = headers[0].split()[1]
if filename == '/':
filename = '/index.html'
try:
fin = open('htdocs' + filename)
content = fin.read()
fin.close()
response = 'HTTP/1.0 200 OK\n\n' + content
except FileNotFoundError:
response = 'HTTP/1.0 404 NOT FOUND\n\nFile Not Found'
return response
|
def isInt( obj ):
"""
Returns a boolean whether or not 'obj' is of type 'int'.
"""
return isinstance( obj, int )
|
def __replace_nbsps(rawtext: str) -> str:
"""Replace nbsps with whitespaces"""
return rawtext.replace('\xa0', ' ')
|
def p_test_subs(t_pos, t_neg):
"""
Calculate proportion of positive outcomes under test condition
:param t_pos: Positive results in Test group
:param t_neg: Negative results in Test group
:return p_test: Proportion of subjects w/ positive outcome under treatment/test condition
"""
total = t_pos+t_neg
p_test = t_pos/total
return p_test
|
def time_fmt(seconds):
""" Utilty function to convert duration to human readable format. Follows
default format of the Unix `time` command. """
return "{:.0f}m{:.3f}s".format(seconds // 60, seconds % 60)
|
def convert_int_list(digit_list):
"""
given a digit list, convert it back to int list
:param digit_list: digit list
:return: integer list
"""
code_str = []
acsii_len = None
acsii_code = ""
acsii_counter = 0
for i in digit_list:
if not acsii_len:
acsii_len = i
acsii_code = ""
acsii_counter = 0
else:
acsii_code += str(i)
acsii_counter += 1
if acsii_counter == acsii_len:
code_str.append(int(acsii_code))
acsii_len = None
return code_str
|
def niam(args):
"""Non-standard entry point."""
return {"greetings": "Hello from a non-standard entrypoint."}
|
def minimum(ints):
"""
Return the minimum in a list of integers. If the list is empty,
return None.
"""
if ints == ():
return None
else:
head, tail = ints
min = minimum(tail)
if min is None or head <= min:
return head
else:
return min
|
def ramp(start,end,n):
"""Return a linear ramp from start to end with n elements"""
return [ (end-start)*x/(float(n)-1)+start for x in range(n) ]
|
def container_status_for_ui(container_statuses):
"""
Summarize the container status based on its most recent state
Parameters
----------
container_statuses : list[V1ContainerStatus]
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1ContainerStatus.md
"""
if container_statuses is None:
return None
assert(len(container_statuses) == 1)
state = container_statuses[0].state
if state.running:
return {"running": {"started_at": state.running.started_at}}
if state.waiting:
return {"waiting": {"reason": state.waiting.reason}}
if state.terminated:
return {"terminated": {
"exit_code": state.terminated.exit_code,
"finished_at": state.terminated.finished_at,
"started_at": state.terminated.started_at,
"reason": state.terminated.reason
}
}
|
def _normalize_output_configuration(config):
"""
Normalize output configuration to a dict representation.
See `get_output_loggers()` documentation for further reference.
"""
normalized_config = {
'both': set(), 'stdout': set(), 'stderr': set()
}
if isinstance(config, str):
if config == 'screen':
normalized_config.update({
'both': {'screen'}
})
elif config == 'log':
normalized_config.update({
'both': {'log'},
'stderr': {'screen'}
})
elif config == 'both':
normalized_config.update({
'both': {'log', 'screen'},
})
elif config == 'own_log':
normalized_config.update({
'both': {'own_log'},
'stdout': {'own_log'},
'stderr': {'own_log'}
})
elif config == 'full':
normalized_config.update({
'both': {'screen', 'log', 'own_log'},
'stdout': {'own_log'},
'stderr': {'own_log'}
})
else:
raise ValueError((
'{} is not a valid standard output config '
'i.e. "screen", "log" or "both"'
).format(config))
elif isinstance(config, dict):
for source, destinations in config.items():
if source not in ('stdout', 'stderr', 'both'):
raise ValueError((
'{} is not a valid output source '
'i.e. "stdout", "stderr" or "both"'
).format(source))
if isinstance(destinations, str):
destinations = {destinations}
for destination in destinations:
if destination not in ('screen', 'log', 'own_log'):
raise ValueError((
'{} is not a valid output destination '
'i.e. "screen", "log" or "own_log"'
).format(destination))
normalized_config[source] = set(destinations)
else:
raise ValueError(
'{} is not a valid output configuration'.format(config)
)
return normalized_config
|
def f(x):
"""A function with an analytical Hilbert transform."""
return 1 / (x ** 2 + 1)
|
def fib(n: int) -> int:
"""
Calculates the n-th Fibonacci number in O(log(n)) time.
See: [Exercise 1.19](https://bit.ly/3Bhv2JR)
"""
if n < 0:
fib_neg = fib(-n)
return fib_neg if (1 - n) % 2 == 0 else -fib_neg
a, b, p, q = 1, 0, 0, 1
while n:
if n % 2 == 0:
p, q = (p ** 2 + q ** 2), (q ** 2 + 2 * p * q)
n //= 2
else:
a, b = (b * q + a * p + a * q), (b * p + a * q)
n -= 1
return b
|
def _iou(box1, box2):
"""
Computes Intersection over Union value for 2 bounding boxes
:param box1: array of 4 values (top left and bottom right coords): [x0, y0, x1, x2]
:param box2: same as box1
:return: IoU
"""
b1_x0, b1_y0, b1_x1, b1_y1 = box1
b2_x0, b2_y0, b2_x1, b2_y1 = box2
int_x0 = max(b1_x0, b2_x0)
int_y0 = max(b1_y0, b2_y0)
int_x1 = min(b1_x1, b2_x1)
int_y1 = min(b1_y1, b2_y1)
int_area = max(int_x1 - int_x0, 0) * max(int_y1 - int_y0, 0)
b1_area = (b1_x1 - b1_x0) * (b1_y1 - b1_y0)
b2_area = (b2_x1 - b2_x0) * (b2_y1 - b2_y0)
# we add small epsilon of 1e-05 to avoid division by 0
iou = int_area / (b1_area + b2_area - int_area + 1e-05)
return iou
|
def GetPreviewResultsPathInGCS(artifacts_path):
"""Gets a full Cloud Storage path to a preview results JSON file.
Args:
artifacts_path: string, the full Cloud Storage path to the folder containing
preview artifacts, e.g. 'gs://my-bucket/preview/results'.
Returns:
A string representing the full Cloud Storage path to the preview results
JSON file.
"""
return '{0}/result.json'.format(artifacts_path)
|
def mybool(string):
"""
Method that converts a string equal to 'True' or 'False' into type bool
Args:
string: (str), a string as 'True' or 'False'
Returns:
bool: (bool): bool as True or False
"""
if string.lower() == 'true':
return True
if string.lower() == 'false':
return False
raise ValueError
|
def grSize(val, n):
"""The number of bits in the Golomb-Rice coding of val in base 2^n."""
return 1 + (val >> n) + n
|
def normalize_quantity(qty, qty_unit: str):
""" takes a qty and a unit (as a string) and returns the quantity in m3/year
accepts:
m3/sec
m3/day
m3/year
Returns None if QUANTITY_UNITS doesn't match one of the options.
"""
if qty_unit is None:
return None
qty_unit = qty_unit.strip()
if qty_unit == 'm3/year':
return qty
elif qty_unit == 'm3/day':
return qty * 365
elif qty_unit == 'm3/sec':
return qty * 60 * 60 * 24 * 365
else:
# could not interpret QUANTITY_UNIT value
return None
|
def commalist(commastr):
"""Transforms a comma-delimited string into a list of strings"""
return [] if not commastr else [c for c in commastr.split(',') if c]
|
def h(p1, p2):
"""Heuristic function"""
x1, y1 = p1
x2, y2 = p2
return abs(x1 - x2) + abs(y1 - y2)
|
def tagIsHidden(tagName):
"""
Check if an tag isn't special for the generator
"""
if tagName=="Script": return True
elif tagName=="Constructor": return True
elif tagName=="Destructor": return True
elif tagName=="Properties": return True
elif tagName=="Declarations": return True
else: return False
|
def euler_from_quarterion(x, y, z, w):
"""
Convert quarterion into euler angles
:param x,y,z,w: quaterion
:type x,y,z,w: quaterion
:return: euler angles (roll, pitch, yaw)
"""
import math
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
X = math.degrees(math.atan2(t0, t1))
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
Y = math.degrees(math.asin(t2))
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y * y + z * z)
Z = math.degrees(math.atan2(t3, t4))
return X, Y, Z
|
def midi_notes_to_tuples(notes):
"""
converts a sequence of pretty_midi notes into a list of (onset,pitch) elements
"""
seq = list()
for n in notes:
seq.append((n.start,n.pitch))
return seq
|
def dict_merge(*dict_list):
"""
Given zero or more dicts, shallow copy and merge them into a new dict, with
precedence to dictionary values later in the dict list.
Helpful mainly before Python 3.5.
https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression
https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations
"""
result = {}
for d in dict_list:
result.update(d)
return result
|
def get_ngrams(sent, n=2, bounds=False, as_string=False):
"""
Given a sentence (as a string or a list of words), return all ngrams
of order n in a list of tuples [(w1, w2), (w2, w3), ... ]
bounds=True includes <start> and <end> tags in the ngram list
"""
ngrams = []
words=sent.split()
if n==1:
return words
if bounds:
words = ['<start>'] + words + ['<end>']
N = len(words)
for i in range(n-1, N):
ngram = words[i-n+1:i+1]
if as_string: ngrams.append('_'.join(ngram))
else: ngrams.append(tuple(ngram))
return ngrams
|
def _sort_key_max_confidence(sample, labels):
"""Samples sort key by the maximum confidence."""
max_confidence = float("-inf")
for inference in sample["inferences"]:
if labels and inference["label"] not in labels:
continue
if inference["confidence"] > max_confidence:
max_confidence = inference["confidence"]
return max_confidence
|
def effectiveResolution(interpolation, sigma_det, feature_size, z, z1, focalLength):
"""
calculate effective resolution
"""
sigma_eff = interpolation*(sigma_det + feature_size*((z*focalLength)/z1))
return sigma_eff
|
def pluralize(n: int, text: str, suffix: str = 's') -> str:
"""Pluralize term when n is greater than one."""
if n != 1:
return text + suffix
return text
|
def cube_vertices(x, y, z, n):
""" Return the vertices of the cube at position x, y, z with size 2*n.
"""
#def cube_vertices(self):
# """ Return the vertices of the cube at position x, y, z with size 2*n.
#
# """
# return [
# x-n,y+n,z-n, x-n,y+n,z+n, x+n,y+n,z+n, x+n,y+n,z-n, # top
# x-n,y-n,z-n, x+n,y-n,z-n, x+n,y-n,z+n, x-n,y-n,z+n, # bottom
# x-n,y-n,z-n, x-n,y-n,z+n, x-n,y+n,z+n, x-n,y+n,z-n, # left
# x+n,y-n,z+n, x+n,y-n,z-n, x+n,y+n,z-n, x+n,y+n,z+n, # right
# x-n,y-n,z+n, x+n,y-n,z+n, x+n,y+n,z+n, x-n,y+n,z+n, # front
# x+n,y-n,z-n, x-n,y-n,z-n, x-n,y+n,z-n, x+n,y+n,z-n, # back
# ]
return [
x-n,y+n,z-n, x-n,y+n,z+n, x+n,y+n,z+n, x+n,y+n,z-n, # top
x-n,y-n,z-n, x+n,y-n,z-n, x+n,y-n,z+n, x-n,y-n,z+n, # bottom
x-n,y-n,z-n, x-n,y-n,z+n, x-n,y+n,z+n, x-n,y+n,z-n, # left
x+n,y-n,z+n, x+n,y-n,z-n, x+n,y+n,z-n, x+n,y+n,z+n, # right
x-n,y-n,z+n, x+n,y-n,z+n, x+n,y+n,z+n, x-n,y+n,z+n, # front
x+n,y-n,z-n, x-n,y-n,z-n, x-n,y+n,z-n, x+n,y+n,z-n, # back
]
|
def three_bytes(address):
"""Convert a 24 bit address to a string with 3 bytes"""
return '%c%c%c' % ((address & 0xff), (address >> 8) & 0xff, (address >> 16) & 0xff)
|
def _lin(x, *p):
"""A generic line function.
Return y = mx + b using p[0] = b, p[1] = m.
Parameters
----------
x: real, array of reals
Point(s) at which to evaluate function.
p: array of size 2
The linear coefficients of the function: p = [b, m].
Returns
-------
y: real, array of reals
The linear function output(s) evaluated at x.
"""
return p[0] + p[1]*x
|
def seq_del(s, i):
"""
Returns a new sequence with i missing. Mysteriously missing from the
standard library.
"""
return s[:i] + s[i+1:]
|
def encode_modified_utf8(u: str) -> bytes:
"""
Encodes a unicode string as modified UTF-8 as defined in section 4.4.7
of the JVM specification.
:param u: unicode string to be converted.
:returns: A decoded bytearray.
"""
final_string = bytearray()
for c in (ord(char) for char in u):
if c == 0x00:
# NULL byte encoding shortcircuit.
final_string.extend([0xC0, 0x80])
elif c <= 0x7F:
# ASCII
final_string.append(c)
elif c <= 0x7FF:
# Two-byte codepoint.
final_string.extend([
(0xC0 | (0x1F & (c >> 0x06))),
(0x80 | (0x3F & c))
])
elif c <= 0xFFFF:
# Three-byte codepoint.
final_string.extend([
(0xE0 | (0x0F & (c >> 0x0C))),
(0x80 | (0x3F & (c >> 0x06))),
(0x80 | (0x3F & c))
])
else:
# Six-byte codepoint.
final_string.extend([
0xED,
0xA0 | ((c >> 0x10) & 0x0F),
0x80 | ((c >> 0x0A) & 0x3f),
0xED,
0xb0 | ((c >> 0x06) & 0x0f),
0x80 | (c & 0x3f)
])
return bytes(final_string)
|
def _check_for_item(lst, name):
"""Search list for item with given name."""
filtered = [item for item in lst if item.name == name]
if not filtered:
return None
else:
return filtered[0]
|
def booleanize_if_possible(sample):
"""Boolean-ize truthy/falsey strings."""
if sample.lower() in ['true', 'yes', 'on', 1]:
sample = True
elif sample.lower() in ['false', 'no', 'off', 0]:
sample = False
return sample
|
def is_end_of_statement(chars_only_line):
"""
Return True if a line ends with some strings that indicate we are at the end
of a statement.
"""
return chars_only_line and chars_only_line.endswith(('rightreserved', 'rightsreserved'))
|
def fibonacci(n):
"""
Calculate the Fibonacci number of the given integer.
@param n If n <= 0 then 0 is assumed.
@return fibonacci number.
"""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
|
def add_out(hout, out, par, x, xm, xp, uncert):
"""
Add entries in out list, according to the wanted uncertainty.
Parameters
----------
hout : list
Names in header
out : list
Parameter values
par : str
Parameter name
x : float
Centroid value
xm : float
Lower bound uncertainty, or symmetric uncertainty
xp : float, None
Upper bound uncertainty if not symmetric uncertainty (None for symmetric)
uncert : str
Type of reported uncertainty, "quantiles" or "std"
Returns
-------
hout : list
Header list with added names
out : list
Parameter list with added entries
"""
if uncert == "quantiles":
hout += [par, par + "_errp", par + "_errm"]
out += [x, xp - x, x - xm]
else:
hout += [par, par + "_err"]
out += [x, xm]
return hout, out
|
def _is_on_line(x, y, ax, ay, bx, by):
"""
Check if point `x`/`y` is on the line segment from `ax`/`ay` to `bx`/`by`
or the degenerate case that all 3 points are coincident.
>>> _is_on_line(0.5, 0.5, 0.0, 0.0, 1.0, 1.0)
True
>>> _is_on_line(0.0, 0.0, 0.0, 0.0, 1.0, 1.0)
True
>>> _is_on_line(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
True
>>> _is_on_line(0.0, 0.5, 0.0, 0.0, 1.0, 1.0)
False
>>> _is_on_line(0.5, 0.0, 0.0, 0.0, 1.0, 1.0)
False
"""
return ((bx - ax) * (y - ay) == (x - ax) * (by - ay) and
((ax <= x <= bx or bx <= x <= ax) if ax != bx else
(ay <= y <= by or by <= y <= ay)))
|
def get_unique_operators(stabilizers: list) -> list:
""" strip leading sign +/- from stabilizer strings """
operator_strings = [x[1:] for x in stabilizers]
return list(set(operator_strings))
|
def generate_neighbor_nid(local_nid: bytes, neighbour_nid: bytes) -> bytes:
"""
Generates a fake node id adding the first 15 bytes of the local node and
the first 5 bytes of the remote node.
This makes the remote node believe we are close to it in the DHT.
"""
return neighbour_nid[:15] + local_nid[:5]
|
def str_to_bool(s):
"""
This function converts a string of True or False into a boolean value.
Args:
s: string
Returns:
boolean value of s
"""
if s == 'True':
return True
elif s == 'False':
return False
|
def group_per_category(bkgs):
"""
Groups a flat list of datasets into sublists with the same category
E.g. [ ttjet, ttjet, ttjet, qcd, qcd ] --> [ [ttjet, ttjet, ttjet], [qcd, qcd] ]
"""
cats = list(set(bkg.get_category() for bkg in bkgs))
cats.sort()
return [ [ b for b in bkgs if b.get_category() == cat ] for cat in cats ]
|
def unquote(input_str, specials, escape='\\'):
"""Splits the input string |input_str| where special characters in
the input |specials| are, if not quoted by |escape|, used as
delimiters to split the string. The returned value is a list of
strings of alternating non-specials and specials used to break the
string. The list will always begin with a possibly empty string of
non-specials, but may end with either specials or non-specials."""
assert len(escape) == 1
out = []
cur_out = []
cur_special = False
lit_next = False
for c in input_str:
if cur_special:
lit_next = (c == escape)
if c not in specials or lit_next:
cur_special = False
out.append(''.join(cur_out))
if not lit_next:
cur_out = [c]
else:
cur_out = []
else:
cur_out.append(c)
else:
if lit_next:
cur_out.append(c)
lit_next = False
else:
lit_next = c == escape
if c not in specials:
if not lit_next:
cur_out.append(c)
else:
out.append(''.join(cur_out))
cur_out = [c]
cur_special = True
out.append(''.join(cur_out))
return out
|
def calc_student_average(gradebook):
"""
Function that will take in a list of students and return
a list of average grades for each student
"""
return [sum(grades)/len(grades) for grades in gradebook]
|
def calc_obj_multi_ss(
objective,
penalty_10=0,
penalty_bal_ipo=0,
penalty_oopo=0,
coeff_10=0,
coeff_bal_ipo=0,
coeff_oopo=0):
"""
calculates objective function for single-panel structures considering the
penalties for the design and manufacturing guidelines
INPUTS
- objective: objective function value of each panel with no
consideration of the penalties for the design rules
- penalty_10: penalty of each panel for the 10% rule constraint
- penalty_bal_ipo: penalty for in-plane orthotropy/balance
- penalty_oopo: penalty of each panel for out-of-plane orthotropy
- coeff_10: weight of the penalty for the 10% rule
- coeff_bal_ipo: weight of the penalty for in-plane orthotropy/balance
- coeff_oopo: weight of the penalty for out-of-plane orthotropy
"""
return objective * (1 + coeff_10 * penalty_10) \
* (1 + coeff_bal_ipo * penalty_bal_ipo) \
* (1 + coeff_oopo * penalty_oopo)
|
def extension(subdir):
"""Does a subdirectory use the .cpp or .cc suffix for its files?"""
return 'cpp' if subdir.startswith('vendor') else 'cc'
|
def command_from_key(key):
"""Return the command correspondign to the key typed (like a giant dictionnary)"""
dict_int_commands = {111: 'forward 30', 113: 'left 30', 114: 'right 30', 116: 'back 30'}
dict_str_commands = {'a': 'sn?', ' ': 'takeoff', '+' : 'land', '8': 'up 30', '2': 'down 30', '6': 'cw 30',
'4': 'ccw 30', 'b': 'battery?', 'f': 'flip f', 'H': 'forward 30', 'A': 'forward 30', 'M': 'right 30',
'C': 'right 30', 'P': 'back 30', 'B': 'back 30', 'K': 'left 30', 'D': 'left 30'}
res_action = dict_int_commands.get(key)
if res_action is None:
return dict_str_commands.get(key)
return res_action
|
def _int(value):
"""
Converts integer string values to integer
>>> _int('500K')
>>> 500000
:param value: string
:return: integer
"""
value = value.replace(",", "")
num_map = {"K": 1000, "M": 1000000, "B": 1000000000}
if value.isdigit():
value = int(value)
else:
if len(value) > 1:
value = value.strip()
value = float(value[:-1]) * num_map.get(value[-1].upper(), 1)
return int(value)
|
def cum_size_distribution(areas, a):
""" Return P[A > a] for the given set of areas.
Extract areas from the hierarchical tree using
areas = [tree.node[n]['cycle_area'] for n in tree.nodes_iter() \
if not tree.node[n]['external']].
"""
return sum([1. for A in areas if A > a])/len(areas)
|
def remove_duplicates(annotations):
"""Removes duplicate annotations. This is mostly used for persons when same
person can be both actor and director.
Args:
annotations (List): List of annotations.
Returns:
List: List of annotations without duplicates.
"""
return [
annotation for i, annotation in enumerate(annotations)
if not any(annotation == ann for ann in annotations[i + 1:])
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.