content stringlengths 42 6.51k |
|---|
def normalize_bound(bound):
"""
Examples
--------
>>> normalize_bound((2.6, 7.2))
(2.6, 7.2)
>>> normalize_bound((None, 7.2))
(-inf, 7.2)
>>> normalize_bound((2.6, None))
(2.6, inf)
>>> normalize_bound((None, None))
(-inf, inf)
This operation is idempotent:
>>> n... |
def upper(s):
"""upper(s) -> string
Return a copy of the string s converted to uppercase.
"""
return s.upper() |
def flatten_int(l):
"""
Flatten a multi-dimensional list to a one-dimensional and convert all values to integers.
:param l: list of lists with values that can be cast to int
:return: flattened int list
"""
return [int(item) for sublist in l for item in sublist] |
def flatten(t):
"""Flatten a list of list"""
return [item for sublist in t for item in sublist] |
def str2bool(value):
"""
Tries to transform a string supposed to represent a boolean to a boolean.
Raises
------
ValueError
If the string is not 'True' or 'False' (case independent)
"""
value = value.upper()
if value == 'TRUE':
return True
elif value == 'FALSE':
... |
def d3(x):
"""Evaluate the estimate 3*x**2+2*x+1."""
return (3*x+2)*x+1 |
def even_bool(num):
"""
Function to check even numbers
Args:
num (int): Number to check if it is even
Return:
return True if the number is even
"""
return num % 2 == 0 |
def load_script_param(script_param):
"""
Create script parameter string to be used in task names and output.
"""
if script_param and "common" not in script_param:
script_param = "common_" + script_param
if script_param:
script_param = script_param.replace(" ", "_")
else:
... |
def getPath(parent_map, start, goal):
"""
Definition
---
Method to generate path using backtracking
Parameters
---
parent_map : dict of nodes mapped to parent node_cost
start : starting node
goal : goal node
Returns
---
path: list of all the points from starting to goal... |
def time_string(seconds):
"""Converts time in seconds to a fixed-width string format."""
days, rem = divmod(int(seconds), 24 * 3600)
hrs, rem = divmod(rem, 3600)
mins, secs = divmod(rem, 60)
return "{0:02},{1:02}:{2:02}:{3:02}".format(days, hrs, mins, secs) |
def get_max_length(matrix, tactics):
"""Given a matrix and a tactics list, returns the maximum column size"""
max_len = 0
for tactic in tactics:
if matrix.get(tactic['x_mitre_shortname']):
if len(matrix[tactic['x_mitre_shortname']]) > max_len:
max_len = len(matrix[tactic... |
def join_lists(*lists):
"""Take some lists and join them in one single list."""
res = []
for k in lists:
for m in k:
res.append(m)
return res |
def get_shader_type(op):
"""Gets shader type from given string."""
shader_type = op.lower()
if shader_type in ("frag", "fragment"):
return "fragment"
elif shader_type in ("geom", "geometry"):
return "geometry"
elif shader_type in ("vert", "vertex"):
return "vertex"
# No t... |
def replace_substring(text: str, replace_mapping_dict: dict):
"""Return a string replaced with the passed mapping dict
Args:
text (str): text with unreplaced string
replace_mapping_dict (dict): mapping dict to replace text
Returns:
str: text with all the substrings replaces
"""... |
def partition(collection, start, end):
"""
Method which partitions the input.
:param collection: Array Inout Array.
:param start: Integer Start Index of Input array.
:param end: Integer End Index of Input array.
"""
pivot = collection[end-1]
pivot_index = start
for index in range(s... |
def get_esa_oa_band_mutations(plan):
"""Work out possible comparable band mutations."""
esa_oa_band_mutations = []
esa_oa_plot_measurements = []
esa_oas = [*plan.get('esa_oa_mappings')]
if len(esa_oas) > 0:
band_prefixes = [*plan.get('esa_oa_mappings')[esa_oas[0]]['PREFIXES']]
band... |
def tuplize(obj):
"""Convert obj to a tuple, without splitting strings"""
try:
_ = iter(obj)
except TypeError:
obj = (obj,)
else:
if isinstance(obj, str):
obj = (obj,)
return tuple(obj) |
def type_csv(data):
"""Format CSV return from list of standard JSON objects."""
import io
import csv
tab_data = list()
mem_file = io.StringIO()
writer = csv.writer(mem_file)
headers = sorted(data[0].keys())
row = [key for key in headers]
writer.writerow(row)
tab_data.append(... |
def format_tuple(values, resolution):
"""Returns the string representation of a geobox tuple."""
format = "%%0.%df" % resolution
return "|".join(format % v for v in values) |
def merge_dicts(*dicts_to_merge: dict):
"""
Merge multiple dictionaries into one.
Leaves originals unchanged.
:param dicts_to_merge: dictionaries to be merged. Multiple dictionaries can be provided.
:return: copy of merged dictionary (originals are left unchanged).
"""
result = {}
for d... |
def check_lat_lon_bounds(latd, latm, lond, lonm):
""" Check the bounds of the given lat, long are within -90 to +90 and -180
to +180 degrees
Paramters
---------
latd, latm, lond, lonm : int or float
Returns
-------
latd, latm, lond, lonm : bounded to -90:90 and -180:180 ... |
def rh_from_ea_es(ea, es):
"""
Calculates relative humidity as the ratio of actual vapour pressure
to saturation vapour pressure at the same temperature (see FAO paper
p. 67).
ea - actual vapour pressure [units don't matter as long as same as es]
es - saturated vapour pressure [units don... |
def slice_epitope_predictions(
epitope_predictions,
start_offset,
end_offset):
"""
Return subset of EpitopePrediction objects which overlap the given interval
and slice through their source sequences and adjust their offset.
"""
return [
p.slice_source_sequence(start_... |
def check_bounding_box(lat_min: float,
lat_max: float,
lon_min: float,
lon_max: float) -> bool:
"""
Check if the provided [lat_min, lat_max, lon_min, lon_max] extents
are sane.
"""
if lat_min >= lat_max:
return False
i... |
def formatted(metadata):
"""Reformats key, value metadata to be written into the
9th column.
"""
out = ''
for k,v in metadata.items():
out += '{} "{}"; '.format(k,v)
out = out.rstrip(' ')
return out |
def move2(course):
"""Meh
>>> move2(EX_INPUT.split('\\n'))
(15, 60, 900)
"""
horiz = 0
depth = 0
aim = 0
for mvt in course:
if not len(mvt):
continue
where, count = mvt.split(" ")
count = int(count)
if where == "forward":
horiz += ... |
def do_replacements(string, replacement_dict):
"""Return the string `string` with all the keys/meta-vars in `replacement_dict`
replaced by their values."""
for key in replacement_dict:
string = string.replace(key, replacement_dict[key])
return string |
def ignoreStrReplace(line, cur, rep, count=None):
"""Wrapper for str.replace to ignore strings"""
# Lazy fix to count being None
if not count:
count = 50
if '"' in line:
#Split string at quotation marks
lsplit = line.split('"')
#Replace items contained within even partiti... |
def is_info_hash_valid(data: bytes, info_hash: bytes) -> bool:
"""
Checks if the info_hash sent by another peer matches ours.
"""
return data[28:48] == info_hash |
def get_upper_left(row, col):
"""Returns row and col of upper left cell in block"""
if row < 3:
yi = 0
elif row < 6:
yi = 3
else:
yi = 6
if col < 3:
xi = 0
elif col < 6:
xi = 3
else:
xi = 6
return yi, xi |
def convert_latitude_to_matrix_idx(latitude: int) -> int:
"""
Purpose: Some HDFs have data stored in a 3600 x 7200 matrix. As a result,
you need the latitude to be converted into an index value. This is more
efficient than converting every index in the matrix to determine if it
in the bounding box.
... |
def fibonacci(n):
"""Calculate the value of nth element in fibonacci sequence
:param n: nth element in fibonacci sequence
:return: the value of nth element in fibonacci sequence
"""
if n < 0:
raise ValueError
if n == 0:
return 0
if n == 1:
return 1
return fibona... |
def conv_if_neg(x):
"""Returns abs of an angle if it's negative"""
if x < 0:
return abs(x), True
return x, False |
def create_access_args(current_actor_id=None, superuser_actor_ids=None):
"""Returns a dict that can be provided to resource registry and datastore find operations to indicate
the caller' actor and system superusers
"""
access_args = dict(current_actor_id=current_actor_id,
superuse... |
def sanitize_mac_for_api(mac):
"""Converts a generalized mac address to one for the API.
Takes any standard mac (case-insensitive, with or without colons) and
formats it to uppercase and removes colons. This is the format for
the API.
:param mac: The input mac.
:returns: The sanitized mac.
... |
def typeAndReplaceFileName(language: str) -> str:
"""
The name of the file where the Type
and replace web application should be saved.
"""
return language + "QuickTypist.html" |
def binary_search(x, v):
"""
Searches for the value v in the sorted array x using a binary search
algorithm. (Not stable, i.e. does not return the first occurrence of v.)
@type x: array
@param x: the (sorted) array to search
@type v: number
@param v: the number to search for
@rty... |
def get_dict_values(dict, key, default_value=''):
"""Get dictionary values accounting for empty values when key exists."""
# Returns False if key doesnt exist, False if value is empty
if bool(dict.get(key)):
return dict.get(key)
else:
return default_value |
def _generate_bmes_label_sequence(sequence_length, start_pos_lst, end_pos_lst):
"""
Assume that O -> 0, B -> 1, M -> 2, E -> 3, S -> 4.
"""
target_symbol_sequence = ["O"] * sequence_length
target_label_sequence = [0] * sequence_length
for tmp_start, tmp_end in zip(start_pos_lst, end_pos_lst):
... |
def dot_product(A, B):
"""
Computes the dot product of vectors A and B.
@type A: vector
@type B: vector
@rtype: number
@return: dot product of A and B
"""
if len(A) != len(B):
raise ValueError("Length of operands do not match")
result = 0.0
for i, v in enumerate(A):
... |
def update_variance(new_data, old_variance, new_mean, old_mean, num_data):
"""Compute a new variance recursively using the old and new mean
From the previously computed variance V_n-1, the new and old mean M_n and
M_n-1 and the new measurement X_n, we compute an update value of the new
variance using t... |
def dms2dd(degrees, minutes, seconds, cardinal):
"""convert coordinate format with degrees, minutes and second to degrees"""
dd = degrees + minutes / 60.0 + seconds / 3600.0
if cardinal in ('S', 'W'):
dd *= -1
return dd |
def list_find(l, e):
"""
Arguments:
l: a list
e: an element to be searched for.
Returns:
The index of the element e in the list, if found,
And -1 if not found.
"""
for i in range(len(l)):
if e == l[i]:
return i
return -1 |
def get_y_fromstab(val,span):
"""Get the y coordinate for plotting the stability curve"""
zero=10
graphrange=180
if span==0:
span=10
return (graphrange-val*(graphrange/span))+zero |
def has_prefix2(word, find):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
for w in find:
if w.startswith(word):
return True
return False |
def decode(string):
"""Decode utf-8 hex to utf-8 string
Unfortunately, there is a limit to how many characters Python can display,
and therefore the maximum amount of utf-8 characters it can detect is 1,114,111.
"""
string = string.replace('\\x', '') # remove all '\x'
result = ""
i = 0
... |
def basic_mesa_f_files(mesa_dir):
"""
Returns list of selected MESA .f90 files & standard_run_star_extras.
These ones provide a nice skeleton of each timestep.
"""
basic_files = ['public/star_lib.f90',
'job/run_star.f90',
'job/run_star.f',
'jo... |
def preprocess(argv):
"""Parse posh `exec' command line.
Args:
inp: raw `exec' command line
Returns:
Tuple suitable for expansion into as self.generic() parameters.
"""
write_file = None
write_flag = argv[1] == '-o'
if write_flag:
if len(argv) == 2:
# i... |
def give_batch_size_choose_probability(episodes, episode, model, original=32):
"""
This method gives probability of choosing action according to the episode number and total number of episode.
:param episodes: total number of episodes
:param episode: current running episode
:param model: model numbe... |
def save_documentation(documentation, path):
"""save documentation to file"""
with open(path, "w") as stream:
stream.write(documentation)
return True |
def to_object(data):
"""Data to object"""
iterable = (list, tuple, set)
if isinstance(data, iterable):
return [to_object(i) for i in data]
if not isinstance(data, dict):
return data
obj = type('Obj', (), {})()
for k, v in data.items():
setattr(obj, k, to_object(v))
... |
def _get_end(posn, alt, info):
"""Get record end position."""
if "END" in info:
# Structural variant
return info['END']
return posn + len(alt) |
def datetime2DateOrNone(value):
"""
Function for converting datetime to date or None
"""
if value is None:
return None
else:
return value.date() |
def percent(value):
"""
find percentage from stats
:param value: tuple (untranslated, translated, total)
:return: percentage
"""
try:
return int((value[1] * 100) / value[2])
except Exception:
return 0 |
def obj(request):
"""A fixture that calls any other fixture when parametrization
with indirect is used.
"""
if hasattr(request, "param") and request.param:
return request.getfixturevalue(request.param) |
def compute_depth(l):
"""
Get maximum number of depth from input list: https://stackoverflow.com/questions/6039103/counting-depth-or-the-deepest-level-a-nested-list-goes-to
"""
if isinstance(l, list):
if l:
return 1 + max(compute_depth(item) for item in l)
else:
... |
def card_average(hand):
"""Return the average of the hand."""
total = 0
count = 0
for card in hand:
total += card
count += 1
return total / count |
def flatten_complete_pass(apass, game_id):
"""Flatten the schema of a completed pass."""
pass_id = apass[0]
pass_data = apass[1]
return {'game_id': game_id,
'pass_type': pass_data['type'],
# 't_half': pass_data['t']['half'],
# 't_min': pass_data['t']['m'],
... |
def as_tuple(x, N):
"""
Coerce a value to a tuple of length N.
Parameters:
-----------
x : value or iterable
N : integer
length of the desired tuple
Returns:
--------
tuple
``tuple(x)`` if `x` is iterable, ``(x,) * N`` otherwise.
"""
try:
X = tuple(x... |
def create_mail_body(messages):
"""status counts to messages
Args:
messages (list): messages
Returns:
body (string): statuses to mail body
"""
body_message = messages[1:]
body = "".join(body_message)
return body |
def _parse_object_status(status):
"""Parse input status into action and status if possible.
This function parses a given string (or list of strings) and see if it
contains the action part. The action part is exacted if found.
:param status: A string or a list of strings where each string contains
... |
def partition(L, v):
"""
Partition list L at value V.
"""
left = []
right = []
for i in range(len(L)):
if L[i] < v:
left.append(L[i])
elif L[i] > v:
right.append(L[i])
return (left, v, right) |
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.... |
def _calc_shakedrop_mask_prob(curr_layer,
total_layers,
mask_prob):
"""Calculates drop prob depending on the current layer."""
return 1 - (float(curr_layer) / total_layers) * mask_prob |
def insert_sort(input_list):
"""Insert sort function."""
if isinstance(input_list, list):
for i in range(len(input_list) - 1):
for j in range(i + 1, 0, -1):
if input_list[j] < input_list[j - 1]:
temp = input_list[j]
input_list[j] = inpu... |
def jinja_filter_param_value_str(value, str_quote_style="", bool_is_str=False):
"""Convert a parameter value to string suitable to be passed to an EDA tool
Rules:
- Booleans are represented as 0/1 or "true"/"false" depending on the
bool_is_str argument
- Strings are either passed through or encl... |
def create_metadata(ipaservers, ipaclients, ads):
"""
Generate example metadata, using FreeIPA as example project.
"""
domain_name = "example.test"
addomain_name = "adexample.test"
fedora = "fedora-31"
ipa_hosts = []
ipadomain = {
"name": domain_name,
"type": "ipa",
... |
def urlify_pythonic(text, length):
"""solution using standard library"""
return text.rstrip().replace(" ", "%20") |
def nottest(f):
"""Mark a function as not a test (decorator)."""
f.__test__ = False
return f |
def is_gov(word):
"""
input: a string
output: boolean value representing if word can be a kind of government
"""
if len(word) == 0:
return False
for letter in word:
if (not letter.isalpha()) and (letter not in ['-', ' ']):
return False
return True |
def _get_settings_data_safe(datapoint_from_settings, column, data_type):
"""Get settings data safe (if data not there, set default ones)"""
if column in datapoint_from_settings:
return datapoint_from_settings[column]
else:
if data_type == int or data_type == float:
return 0
... |
def determinant(a, b, c, d, e, f, g, h, i):
"""Calculate the determinant of a three by three matrix.
Where the matrix contents match the parameters, like so:
|a b c|
|d e f|
|g h i|
"""
return a*(e*i - f*h) - b*(d*i - f*g) + c*(d*h - e*g) |
def line(args):
"""Line"""
return args[0] + args[1] - 2.0 |
def data_validator(messages):
"""
Returns True if all fields contain valid data, otherwise False if any field contains
invalid data
"""
for key, value in messages.items():
if value != 'Valid':
return False
return True |
def get_gate_info(gate):
"""
gate: str, string gate. ie H(0), or "cx(1, 0)".
returns: tuple, (gate_name (str), gate_args (tuple)).
"""
gate = gate.strip().lower().replace("cnot", "cx")
i = gate.index("(")
gate_name, gate_args = gate[:i], eval(gate[i:])
try: len(gate_args)
ex... |
def init_dict_brackets(first_level_keys):
"""Initialise a dictionary with one level
Parameters
----------
first_level_keys : list
First level data
Returns
-------
one_level_dict : dict
dictionary
"""
one_level_dict = {}
for first_key in first_level_keys:
... |
def scale_down(left, right):
"""
Normalise scaling factor between 0 and 1.
:arg float left, right: Scaling factors.
:return: Tuple of normalised scaling factors.
:rtype: float, float
"""
factor = max(left, right)
return left / factor, right / factor |
def golden_ratio(figwidth=5):
"""Return the figure size (width, height) following the golden ratio given the width figwidth (default = 5)"""
Phi = 1.61803
a = figwidth / Phi
return [ figwidth, a ] |
def rirange(a, b, rev):
"""Reversible inclusive range."""
if rev:
return range(b, a - 1, -1)
return range(a, b + 1) |
def _is_file_relevant(file_name: str, problem_name: str, graph_type: str, p_depth: int):
"""Check if a filename provided matches the description of a problem instance."""
return problem_name in file_name and "p=" + str(p_depth) in file_name and graph_type in file_name |
def _ExtractKeyValuePairsFromLabelsMessage(labels):
"""Extracts labels as a list of (k, v) pairs from the labels API message."""
labels = [] if labels is None else labels
return [(label.key, label.value) for label in labels] |
def format_word(word: str) -> str:
"""
formats a word by removing linebreaks changing it to lowercase
:param word: the word to format
:return: the formatted word
"""
word = word.lower()
lbi = word.find("\n")
if lbi > 0:
word = word[:lbi]
return word |
def _convert_dict_to_list_of_dict(inputs_dict):
"""
Convert a dictionary with multiple keys (used as model inputs) into a list
of individual dictionaries containing one element for each key
Args:
inputs_dict (dict):
a dictionary with multiple keys (used as model inputs), values are
... |
def validate_int(num):
"""Function: validate_int
Description: Converts value to int and then check to see if it is an int.
Arguments:
(input) num -> Integer value for testing.
(output) Return True|False. False if value is not an integer.
"""
try:
isinstance(int(num), ... |
def validate_sso_password(value):
"""Raise exception is SSO password exceeds length."""
if value and len(value) > 128:
return "have length less than or equal to 128"
return "" |
def markup(pre, string):
"""
By Adam O'Hern for Mechanical Color
Returns a formatting string for modo treeview objects.
Requires a prefix (usually "c" or "f" for colors and fonts respectively),
followed by a string.
Colors are done with "\03(c:color)", where "color" is a string represe... |
def merge_list(word_lists: list) -> dict:
"""this function merges all the word_list(dictionary)
:param word_lists: an array contain all the word_list(dictionary type)
:return: the merged word list (dictionary type)
"""
merged_list = {}
for word_list in word_lists:
for key in list(word_l... |
def car_size_exist(payload):
"""renvoi la categorie de la voiture"""
name_car_size = payload.get('car_size')
if name_car_size is None:
return (None)
else:
size = {'petite voiture': '1',
'moyenne voiture': '2',
'grande voiture': '3'
}
return siz... |
def intersection(line1, line2):
"""pysimm.calc.intersection
Finds intersection between two 2D lines given by two sets of points
Args:
line1: [[x1,y1], [x2,y2]] for line 1
line2: [[x1,y1], [x2,y2]] for line 2
Returns:
x,y intersection point
"""
xdiff = (line1[0][0] - lin... |
def ar_days_in_topk(day_range, ar_dict):
"""
Accepts a day range dictionary
And a nested dict with articles as keys
And as values varying numbers of k,v pairs
Returns the article dictionary with a new k,v pair value
that counts the number of existing k,v pairs in that article dict
... |
def check_host(host):
""" Helper function to get the hostname in desired format """
if not ('http' in host and '//' in host) and host[len(host) - 1] == '/':
return ''.join(['http://', host[:len(host) - 1]])
elif not ('http' in host and '//' in host):
return ''.join(['http://', host])
elif host[len(host) - 1] ==... |
def _hex_to_bytes(cmd):
"""
A helper function to convert a hexadecimal byte to a bytearray.
"""
return bytes([cmd]) |
def soft_thresholding(v, threshold):
"""
soft thresholding function
:param v: scalar
:param threshold: positive scalar
:return: st(v)
"""
if v >= threshold:
return (v - threshold)
elif v <= - threshold:
return (v + threshold)
else:
return 0 |
def trigger_dict(ts_epoch):
"""A dictionary representing a date trigger."""
return {"run_date": ts_epoch, "timezone": "utc"} |
def mysql_quote(x):
"""Quote the string x using MySQL quoting rules. If x is the empty string,
return "NULL". Probably not safe against maliciously formed strings, but
our input is fixed and from a basically trustable source."""
if not x:
return "NULL"
x = x.replace("\\", "\\\\")
x = x.r... |
def convert_stupid_js_import_to_stupid_js_import(txt):
""" this is GWT-to-PyJS-specific conversion: support of assembly-like
direct insertion of javascript. again, it's one of the few bits
of non-generic java-to-python
"""
txt = txt.replace("/*-{", '{\nJS("""')
txt = txt.replace("}-*/",... |
def make_description_from_params(description, formula):
"""
Generate column description
"""
final_description = ""
if description:
final_description += f"{description}\n\n"
if formula:
final_description += f"formula: {formula}"
return final_description |
def __wrap_nonsense_request(request, is_nonsense):
"""
Wrap the given result of an "estimate nonsense" request in a JSON-like dict
Args:
request: The request that was processed
is_nonsense: True if the question is nonsense
False if the question is not nonsense
... |
def c2f(c):
"""Celsius to Fahrenheit"""
return 9/5*c + 32 |
def evaluate_candidate_generation(list_corrections, list_candidates):
"""Returns the recall (in %) of candidate generation methods.
Args:
list_corrections (list): List of tuples with (noisy_word, correction).
list_candidates (list): List of list(candidates).
BOTH LISTS MUST BE ALLIGNED!... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.